Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the client port (in C) after a call to connect

I am browsing some source code which connects to a remote host on port P(using TCP). After the call to connect,(assuming successful), I would like to discover the client port of the connection (i.e the client port). In truth, I'm browsing the openssh source, in sshconnect.c, there is a function ssh_connect which calls timeout_connect. I have the remote host ip,port, local ip but would like to know the local (client) port after a successful connect.

I hope I have been clear and thank you for your answers Regards Sapsi

like image 737
Fishy Avatar asked Mar 02 '10 01:03

Fishy


People also ask

How do I find the client port number for server socket programming?

This can be done using a bind() system call specifying a particular port number in a client-side socket. Below is the implementation Server and Client program where a client will be forcefully get assigned a port number.

How is the port number of the client assigned?

The selected port number is assigned to the client for the duration of the connection, and is then made available to other processes. It is the responsibility of the TCP/IP software to ensure that a port number is assigned to only one process at a time.

How does client know server port?

When the server application initializes, it uses the bind() socket call to identify its port number. A client application must know the port number of a server application in order to contact it.

What port does client use?

The default values for client request ports are 80 for HTTP traffic and 443 for HTTPS traffic.


2 Answers

Try feeding the client socket file descriptor to getsockname, something like so

struct sockaddr_in local_address;
int addr_size = sizeof(local_address);
getsockname(fd, &local_address, &addr_size);

Then you can pick apart the address structure for the IP and port.

like image 72
JustJeff Avatar answered Oct 15 '22 00:10

JustJeff


You can use a struct sockaddr_in to hold client's info. Also, you can use the getsockname function to get your client's current address. Like this:

struct sockaddr_in client;
socklen_t clientsz = sizeof(client);

[... after connect() ...]

getsockname(socket_descriptor, (struct sockaddr *) &client, &clientsz);

printf("[%s:%u] > ", inet_ntoa(client.sin_addr), ntohs(client.sin_port));
                   /* client address                  client port      */

Result:

[127.0.0.1:58168] > (I was running my program locally)

like image 24
Erick Giffoni Avatar answered Oct 15 '22 00:10

Erick Giffoni