利用socket与www.baidu.com建立连接 发送get数据 但是收到的数据是0 麻烦帮忙看下下面的代码 谢谢
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self Connect:@"www.baidu.com" content:nil];
}
-(NSMutableString *)makeHttpHeader:(NSString*)hostName
{
NSMutableString * header = [[NSMutableString alloc] init];
[header appendFormat:@"GET "];
[header appendFormat:@"HTTP/1.1\r\n"];
[header appendFormat:KENTER];
[header appendFormat:@"Host:"];
[header appendFormat:hostName];
[header appendFormat:@"\r\n\r\n"];
NSLog(@"%@",header);
return header;
}
-(NSString*)getIpAddressorHost:(NSString*)theHost
{
struct hostent * host = gethostbyname([theHost UTF8String]);
if( !host )
{
herror("resolv");
return NULL;
}
struct in_addr ** list = (struct in_adr**)host->h_addr_list;
NSString * addressString = [NSString stringWithCString:inet_ntoa(*list[0])];
NSLog(@"IPAddr is:%@",addressString);//这里的 IP地址 是对的
return addressString;
}
-(void)Connect:(NSString*)hostName content:(NSString*)contentSended
{
if((sockfd = socket(AF_INET,SOCK_STREAM,0))== -1 )
{
perror("SOCKET error");
exit(1);
}
their_addr.sin_family = AF_INET;
their_addr.sin_addr.s_addr = inet_addr([[self getIpAddressorHost:hostName] UTF8String]);
their_addr.sin_port = htons(80);
bzero(&(their_addr.sin_zero),8);
int conn = connect(sockfd , (struct sockaddr*)&their_addr , sizeof(struct sockaddr));
NSLog(@"conn:%d",conn);
if( conn != -1 )
{
char readBuf[512]={0};
int recvLen = 0;
NSMutableString *httpContent = [self makeHttpHeader:hostName];