sockaddr.sin_port = 1337 doesn't match the "real" opened port
Asked Answered
K

2

5

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

However when trying to connect to 127.0.0.1:1337, I get a connection refused message :

(UNKNOWN) [127.0.0.1] 1337 (?) : Connection refused

However a simple netstat -tcpan shows me that a port is indeed opened :

tcp 0 0 0.0.0.0:14597 0.0.0.0:* LISTEN

If I set sin_port with much higher ports it seems to work properly though.

What am I missing here ? Why isn't the 1337 port opened ? It seems to be free too.

Kachine answered 13/10, 2016 at 7:25 Comment(1)
you have to use htons for the port to switch the byte orderSandra
C
11

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
Coliseum answered 13/10, 2016 at 7:41 Comment(0)
F
2
listen(serv, 0);

The second argument to listen is backlog and if we look at the documentation for listen :

The backlog argument defines the maximum length to which the queue of pending connections for sockfd may grow. If a connection request arrives when the queue is full, the client may receive an error with an indication of ECONNREFUSED or, if the underlying protocol supports retransmission, the request may be ignored so that a later reattempt at connection succeeds.

ECONNREFUSED is exactly the error message you're getting because the backlog is full ( it can hold 0 connections so it's always full ). You should increase that number to at least 1 but a higher amount might be better listen(serv, 10);.

Fayre answered 13/10, 2016 at 7:29 Comment(1)
Okay, but then why can I connect to the port shown by netstat ? So a port is opened at the right address, sends me the ECONNREFUSED, but another is opened at the wrong port but I can connect to it ?Kachine

© 2022 - 2024 — McMap. All rights reserved.