Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Port Problem

Status
Not open for further replies.

matmil

Technical User
Joined
Mar 18, 2005
Messages
6
Location
US
I am currently sending out UDP traffic on a random port by using:-

local.sin_family = AF_INET;
local.sin_addr.s_addr = htonl(INADDR_ANY);
local.sin_port = htons(0);

As you know this picks a random, unused port to send traffic from...

I then want to listen on that port which was randomly selected for return traffic...

How can I get which port the computer randomly chose as local.sinp_port always remains 0.

Cheers,
Matt
 
MatMIl:
you can use 'getsockname' to retreive that info ...

Code:
struct sockaddr_in cli_addr;    /* client socket stuff */

  /*
   * Since the connect call assigns a random address to the local end
   * of this connection, let's use 'getsockname' to see what it assigned.
   * Note that 'addrlen' needs to be passed in as a pointer, because
   * getsockname returns the actual length of the address.
   */
    climsglen = sizeof(cli_addr);
    if (getsockname(clisocket, (struct sockaddr *) &cli_addr, &climsglen)) {
        perror("getsockname");
    }

   /*
    * The port number must be converted first to host byte order before
    * printing.  On most hosts, this is not necessary, but the ntohs() call
    * is included here so that this program could easily be ported to a different host.
    */
    log_msg("Connected to %s on port %u.", hostname, ntohs(cli_addr.sin_port));
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top