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