Crocode
Crocode

Reputation: 3134

How do I get client's port number from the server?

I have written a simple client-server program. I am able to print the port number of client in the client program. The values are dynamic.

But when I try to print it in the server program, it gives me the port number of the server and not the client.

connfd = accept(listenfd, (struct sockaddr*) &cliaddr, &clilen);

cout<<"Server: Server's Port: "<< ntohs(servaddr.sin_port)<<endl; /*23112*/
cout<<"Server: Client's Port: "<< ntohs(cliaddr.sin_port)<<endl; /*23112*/

I am using the same in client program, and it is printing the random ports correctly. I have initialized them this way:

struct sockaddr_in cliaddr, servaddr;
socklen_t clilen = sizeof(cliaddr);

Upvotes: 0

Views: 1688

Answers (1)

user207421
user207421

Reputation: 310840

You need to initialize 'clilen':

The addrlen argument is a value-result argument: the caller must initialize it to contain the size (in bytes) of the structure pointed to by addr; on return it will contain the actual size of the peer address.

Upvotes: 1

Related Questions