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

Posted by Dr Dork on Stack Overflow See other posts from Stack Overflow or by Dr Dork
Published on 2010-03-22T22:47:56Z Indexed on 2010/03/22 22:51 UTC
Read the original article Hit count: 277

Filed under:
|
|

Hello! 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!

© Stack Overflow or respective owner

Related posts about sockets

Related posts about unix