Jayzcode
Jayzcode

Reputation: 1325

Different Port Number displayed by server and client for a common Port number

I have server and client Program written in C, and it is working fine, but I am not able to figure out reason for the behaviour explained below:

server.c

server_address.sin_family = AF_INET;
server_address.sin_port = htons(9374);
server_address.sin_addr.s_addr = htonl(INADDR_ANY);  
server_len = sizeof(server_address);    
bind(server_sockfd, (struct sockaddr *)&server_address, server_len);

getsockname (server_sockfd, (struct sockaddr *)&server_address, &server_len);
printf("server port = %d\n", server_address.sin_port); 
printf("Server Waiting......\n");
listen(server_sockfd, 5);

client.c

address.sin_family = AF_INET;
address.sin_port = htons(9374);

int length, result;
length = sizeof(address);

result = connect(sockfd, (struct sockaddr *)&address, length);

getsockname(sockfd, (struct sockaddr *)&address, &length);
printf("Connecting to Port = %d \n", address.sin_port);

outputs On Server Side:

[root@dhcppc1 Socket]# ./server
server port = 40484 
Server Waiting......

Output on Client Side:

[root@dhcppc1 Socket]# ./client
Connecting to Port = 18576 

My question is:

Though same the port number (9374) and operations are implemented in server and client code, yet Why do they show different port numbers( like 40484 on server and 18576 on client)?

Upvotes: 3

Views: 3331

Answers (1)

nos
nos

Reputation: 229342

getsockname() returns the local port number of the connection. A TCP connection has two port, one for each end of the connection.

Since your client has not called bind() to select a local port, the system chose one at random for you.

So your server program is displaying its own port it is listening to, and your client displays its own port it is sending from.

Note also that you are printing out the port number in network endian format, to print it out in host endian, use ntohs() like this (and similar on the client)

printf("server port = %d\n", ntohs(server_address.sin_port));

This will make the server print out 9374

If you want to fetch the server port on your client, use getpeername() instead of getsockname() - then again, you already know the server port as that's the port you connected to, 9374.

Upvotes: 4

Related Questions