c – Connect: Socket operation on non-socket

c – Connect: Socket operation on non-socket

I see the problem. Its 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).

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 errorn);
        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.

c – Connect: Socket operation on non-socket

Leave a Reply

Your email address will not be published.