C语言 Connect:非socket上的socket操作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14721005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:15:56  来源:igfitidea点击:

Connect: Socket operation on non-socket

csocketsunixnetworking

提问by Nmzzz

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)

我是 unix 网络编程的新手,我尝试编写一个程序来连接到 Google 的服务器。但是,在使用 connect() 函数时出现错误。(操作系统:OS X)

Connect error: Socket operation on non-socket

连接错误:非套接字上的套接字操作

I have worked at it for 4 hours but I could not find out the problem. Here is my code:

我已经工作了 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;
}

回答by selbie

I see the problem. It's this line:

我看到了问题。这是这一行:

if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0) == -1))

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(...) == -1),sockfd 被初始化为“0”。

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)

Notice the subtle difference.

注意细微的差别。