Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Find the port the kernel chose

Posted on 2006-06-07
3
Medium Priority
?
282 Views
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(...);
bind(s,in,sizeof(in));
listen(s,backlog);
/*accept() in some new thread*/

connect(c,in,sizeof(in));
0
Comment
Question by:nerdmike
1 Comment
 
LVL 3

Accepted Solution

by:
Mikeh926 earned 2000 total points
ID: 16859867
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.

Mike.
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

If you’re thinking to yourself “That description sounds a lot like two people doing the work that one could accomplish,” you’re not alone.
This article will show how Aten was able to supply easy management and control for Artear's video walls and wide range display configurations of their newsroom.
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 seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

577 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