Skip to content
Advertisement

C socket programming errors

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 ?

JavaScript

Advertisement

Answer

Due to operator precedence, the expression

JavaScript

is actually equal to

JavaScript

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:

JavaScript

The same needs to be done for the connect call and the comparison there.

Advertisement