Reputation: 347
In the server program I'm binding IP 127.0.0.1 and port 1234.
However when I use netstat -lntpu to find what process is listening to what port..I find my server program listed but strikingly the port number is not what I've assigned !
Here's the line what I'm referring to
Proto | Recv-Q | Send-Q | Local Address | Foreign Address | State | PID/Program_name
tcp | 0 | 0 | 127.0.0.1:53764 | 0.0.0.0:* | LISTEN | 10545/server
So if I binded the socket with 1234 why is the netstat listing 53764 ?
I'm able to transfer data successfully from client to server and back. But this is looking strange here !!
Here's the binding code
struct sockaddr_in ser_addr
ser_addr.sin_family=AF_INET;
ser_addr.sin_port=1234;
ser_addr.sin_addr.s_addr=inet_addr("127.0.0.1");
sd=socket(AF_INET,SOCK_STREAM,0);
ret=bind(sd,(struct sockaddr*)&ser_addr,sizeof(ser_addr));
listen(sd,3);
Upvotes: 0
Views: 350
Reputation: 881443
It has to to do with the byte ordering of your port setting.
The value 1234
is made up of the two octets {4, 210}
while {210, 4}
gives you your 53764
value (a).
When specifying the port address, you should be aware that it is a 16-bit port number, network byte ordered
(from W. Richard Stevens' UNIX Network Programming (b)). Network byte ordering is a big-endian scheme whereas your implementation appears to have a little-endian scheme, hence you need to switch the octets around:
ser_addr.sin_port = htons (1234);
In fact, you should do it that way even if the byte ordering is the same since it becomes, in that case, a no-operation. The htons
is how you (quoting from the same book mentioned above) "convert host-to-network, short integer".
(a) This is so because the order of the octets within a data type dictate how the value is calculated:
4 * 256 + 210 = 1234 // or use (x << 8 | y) rather than
210 * 256 + 4 = 53764 // (x * 256 + y) if you wish
(b) A book you really should have if you're going to be doing any serious networking development.
Upvotes: 4