I am trying to make a very simple server that accept a connection.
int sock, serv;
struct sockaddr_in in_sock;
serv = socket(AF_INET, SOCK_STREAM, 0);
in_sock.sin_addr.s_addr = 0;
in_sock.sin_port = 1337;
in_sock.sin_family = AF_INET;
bind(serv, (struct sockaddr *)&in_sock, sizeof(in_sock));
listen(serv, 0);
client = accept(serv, 0, 0);
(UNKNOWN) [127.0.0.1] 1337 (?) : Connection refused
netstat -tcpan
tcp 0 0 0.0.0.0:14597 0.0.0.0:* LISTEN
The port number field in struct sockaddr_in
is stored in network byte order. This means that you must use htons()
when storing a value to it:
in_sock.sin_port = htons(1337);
Otherwise, the port number will be left byte-swapped. Which is exactly what has happened here:
1337 = 0x0539
14597 = 0x3905