Find the port the kernel chose

Posted on 2006-06-07
Last Modified: 2010-04-17
When you set up a socket to listen on an address, and you choose "anything available" as the port, how can you tell which port it was?

See the code for an example of what I mean

struct sockaddr_in in, out;

int s,c;

in.sin_family = AF_INET;
in.s_addr = htonl(INADDR_LOOPBACK);
in.s_port = 0; /*anything available*/

out.sin_family = AF_INET;
out.s_addr = htonl(INADDR_LOOPBACK);
out.s_port = /*what do I put here?*/   <=========

s = socket(...);
/*accept() in some new thread*/

Question by:nerdmike
    1 Comment
    LVL 3

    Accepted Solution

    after calling bind(), call getsockname(). Apart from getting the name, this will fill in a SOCKADDR structure that contains both the IP Address and Port number that was allocated.


    Featured Post

    IT, Stop Being Called Into Every Meeting

    Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

    Join & Write a Comment

    INTRODUCTION We all know how to code. But at times you simply want to insert a common code block into your existing code and amend it as per your requirements. This tool not only saves you time but also saves you the pain of typing it all out aga…
    This article will show, step by step, how to integrate R code into a R Sweave document
    An introduction to basic programming syntax in Java by creating a simple program. Viewers can follow the tutorial as they create their first class in Java. Definitions and explanations about each element are given to help prepare viewers for future …
    In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…

    733 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    22 Experts available now in Live!

    Get 1:1 Help Now