Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I obtain the local TCP port and IP Address of my client program?

Tags:

c

unix

sockets

I'm prepping for a simple work project and am trying to familiarize myself with the basics of socket programming in a Unix dev environment. At this point, I have some basic server side code and client side code setup to communicate. Currently, my client code successfully connects to the server code and the server code sends it a test message, then both quit out. Perfect! That's exactly what I wanted to accomplish. Now I'm playing around with the functions used to obtain info about the two environments (server and client). I'd like to obtain the local IP address and dynamically assigned TCP port of the client. The function I've found to do this is getsockname()...

//setup the socket
if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) 
{
   perror("client: socket");
   continue;
}

//Retrieve the locally-bound name of the specified socket and store it in the sockaddr structure
sa_len = sizeof(sa);
getsock_check = getsockname(sockfd,(struct sockaddr *)&sa,(socklen_t *)&sa_len) ;
if (getsock_check== -1) {
    perror("getsockname");
    exit(1);
}

printf("Local IP address is: %s\n", inet_ntoa(sa.sin_addr));
printf("Local port is: %d\n", (int) ntohs(sa.sin_port));

but the output is always zero...

Local IP address is: 0.0.0.0
Local port is: 0

does anyone see anything I might be or am definitely doing wrong?

Thanks so much in advance for all your help!

like image 233
BeachRunnerFred Avatar asked Dec 17 '22 02:12

BeachRunnerFred


2 Answers

From the looks of your code you are not doing connect or accept on the socket. Until you have done this the data you get from getsockname is undefined.

like image 165
Daniel Karling Avatar answered Dec 29 '22 00:12

Daniel Karling


I don't think you can meaningfully call getsockname in this context until you've called connect() - the kernel doesn't bind it to a particular port until it needs to (or is told to do so explicitly), and the local address is chosen based on the routing table, and hence the destination.

like image 38
MarkR Avatar answered Dec 29 '22 00:12

MarkR