我是 unix 网络编程的新手,我试图编写一个程序来连接到 Google 的服务器。但是,在使用 connect() 函数时出现错误。(操作系统:OS X)
连接错误:非套接字上的套接字操作
我已经工作了 4 个小时,但我找不到问题所在。这是我的代码:
#define SERVPORT 80
int main (int argc, char **argv)
{
int i, sockfd;
struct hostent *host;
struct sockaddr_in serv_addr;
if ( (host = gethostbyname(argv[1])) == NULL) {
printf("gethostbyname error\n");
exit(1);
}
for (i = 0; host->h_addr_list[i]; i++) {
if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0) == -1)) {
printf("socket error\n");
exit(1);
}
bzero(&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(SERVPORT);
serv_addr.sin_addr = *( (struct in_addr *)host->h_addr_list[i]);
const char *ip = inet_ntoa(serv_addr.sin_addr);
printf("connect to %s\n", ip);
if (connect(sockfd, (struct sockaddr *) &serv_addr,
sizeof(struct sockaddr)) == -1) {
printf("connect error:%s\n", strerror(errno));
exit(1);
}
}
return 0;
}