我正在学习Beej的套接字教程为什么下面对socket
的调用在iPhone模拟器中不起作用
int status;
struct addrinfo hints;
struct addrinfo *servinfo;
char ipstr[INET6_ADDRSTRLEN];
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
if ((status = getaddrinfo("www.yahoo.com",
"80",
&hints,
&servinfo)) != 0) {
fprintf(stderr, "getaddrinfo error: %sn", gai_strerror(status));
exit(1);
}
for(struct addrinfo *p = servinfo; p != NULL; p = p->ai_next) {
void *addr;
char *ipver;
if (p->ai_family == AF_INET) {
struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;
addr = &(ipv4->sin_addr);
ipver = "IPv4";
} else {
struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr;
addr = &(ipv6->sin6_addr);
ipver = "IPv6";
}
inet_ntop(p->ai_family, addr, ipstr, sizeof(ipstr));
printf(" %s: %sn", ipver, ipstr);
int socketfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
if (socketfd)
printf("errno: %dn", errno);
}
freeaddrinfo(servinfo);
上述代码的输出为:
IPv4: 72.30.38.140
errno: 2
IPv4: 72.30.2.43
errno: 2
errno 2为No such file or directory
。我不知道该怎么解释。
错误在这一行:
if (socketfd) {
这应该是:
if (socketfd == -1) {
由于socket()
在出错时返回-1,而在成功时返回0(如前所述:https://stackoverflow.com/a/1879234/22471)