UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

#1 2002-07-25 08:19 PM

HectorLasso
Administrator
From: Colombia
Registered: 2002-06-12
Posts: 353

Re: 3.9 - How can I determine the local port number?

6

From: Fajun Shi (fajun@cs.msstate.edu):

Hi, my question is: When I write a client, how can I know the port number that the socket bound in my machine?

From: Jörg Jensch

Hi!

Use getsockname(3N) to find out the local port
number your client application uses. Here is a
simple example:

len = sizeof ( server ); 
if ( getsockname ( sock, &server, &len ) < 0 ) 
  perror ( "getsockname" ); 
  else 
    fprintf ( stderr, "local port number before connect: %d\n", ntohs ( ((struct sockaddr_in *)&server)->sin_port )); 
     
    connected = connect(sock, (struct sockaddr *) &address, sizeof(address)); 
     
    len = sizeof ( server ); 
    if ( getsockname ( sock, &server, &len ) < 0 ) 
      perror ( "getsockname" ); 
      else 
        fprintf ( stderr, "local port number after connect : %d\n", ntohs ( ((struct sockaddr_in *)&server)->sin_port ));

         
---------------------------------------
         
And here is the output I retrieve:

local port number before connect: 0 
        local port number after connect : 34994

         
As can be seen, the system do not bind any local port number for a socket before the client calls connect().

Greetings
         
Jayjay

Offline

Board footer

Powered by FluxBB