tags:

views:

99

answers:

2

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!

+5  A: 

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.

Daniel Karling
Beat me by 6 secs :)
MarkR
wonderful, that fixed it. thanks daniel, mark!
BeachRunnerJoe
+1  A: 

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.

MarkR
thanks for your help!
BeachRunnerJoe