It’s been an hour since I started looking for THE error. I just started C sockets. The program exits with code -1
after printing “Error 1 connection error”. The server in online, it’s a netcat server. Where did I messed up ?
#include <stdio.h> #include <sys/socket.h> #include <stdlib.h> #include <netinet/in.h> #include <string.h> #define HOST "127.0.0.1" #define PORT 4444 int main(int argc, const char *argv[]) { struct sockaddr_in addr; int sock = 0; int ret; struct sockaddr_in server_addr; char *msg = "Hello world !n"; char inBuffer[1024] = { 0 }; if (sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP) < 0) { printf("Error %d socket creating.n", sock); exit(-1); } else { memset(&server_addr, '0', sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_port = htons(PORT); if (ret = inet_pton(AF_INET, HOST, &server_addr.sin_addr) <= 0) { printf("Error %d unsuported address: %dn", ret); exit(-2); } else { if (ret = connect(sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) { printf("Error %d connection errorn", ret); exit(-3); } else { send(sock, msg, strlen(msg), 0); read(sock, inBuffer, 1024); printf("%sn", inBuffer); return 0; } } } }
Advertisement
Answer
Due to operator precedence, the expression
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP) < 0
is actually equal to
sock = (socket(AF_INET, SOCK_STREAM, IPPROTO_TCP) < 0)
That is, you assign the result of the comparison socket(AF_INET, SOCK_STREAM, IPPROTO_TCP) < 0
to the variable sock
. The result of that comparison will always be either 0
(for false) or 1
(for true). Neither 0
nor 1
should be a valid socket.
You need to explicitly add parentheses for the assignment:
(sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0
The same needs to be done for the connect
call and the comparison there.