Connect:非socket上的socket操作 [英] Connect: Socket operation on non-socket
问题描述
我是 unix 网络编程的新手,我尝试编写一个程序来连接到 Google 的服务器.但是,在使用 connect() 函数时出现错误.(操作系统:OS X)
I'm new to unix network programming and I have tried to write a program to connect to Google's server. However, I got a error while using the connect() function. (OS: OS X)
连接错误:非套接字上的套接字操作
我已经工作了 4 个小时,但我找不到问题所在.这是我的代码:
I have worked at it for 4 hours but I could not find out the problem. Here is my code:
#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;
}
推荐答案
我看到了这个问题.这是这一行:
I see the problem. It's this line:
if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0) == -1))
== 运算符优先于 = 运算符.仔细看看你在那个表达式上构造括号的方式,看看我的意思.由于被分配了一个布尔表达式 (socket(...) == -1),sockfd 被初始化为0".
The == operator has precedence over the = operator. Look at the way you have the parentheses structured on that expression a bit more carefully to see what I mean. sockfd is getting initialize to "0" as a result of being assigned a boolean expression (socket(...) == -1).
将socket初始化改成这样:
Change the socket initialization to this:
for (i = 0; host->h_addr_list[i]; i++)
{
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1)
{
printf("socket error\n");
exit(1);
}
或者,如果您更喜欢同一行方法中的分配和比较",您可以这样说:
Or if you prefer the "assign and compare" on the same line approach, you can probably say this:
if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
注意细微的差别.
这篇关于Connect:非socket上的socket操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!