views:

227

answers:

2

How to get List of free port number in VC++?

Aslo i want to check wether user define port number is free or not ?

+1  A: 

(I'm assuming you're talking about TCP/IP ports)

There ain't no such thing as a list of free port numbers. But utilities like netstat.exe (I like to use netstat /a /n /p tcp) give you a list of used port numbers. The free port numbers are all port numbers between 1 and 65535 inclusive that are not used.

If you can get that list of used port numbers programmatically, your problem is solved. If I were really hard up, I'd capture the output from netstat and parse it.

Update:

(from Wikipedia) http://en.wikipedia.org/wiki/Netstat:

On the Windows platform, netstat information can be retrieved by calling the GetTcpTable and GetUdpTable functions in the IP Helper API, or IPHLPAPI.DLL. Information returned includes local and remote IP addresses, local and remote ports, and (for GetTcpTable) TCP status codes. In addition to the command-line netstat.exe tool that ships with Windows, there are GUI-based netstat programs available.

There's also some more helpful information in that Wikipedia article. A nice explanation of the stati returned is also here: http://commandwindows.com/netstat.htm .

Carl Smotricz
+2  A: 

The only way to know for certain whether a port number is "free" is to actually try to bind() to it.

Recall that a port number only means something in the context of a particular interface address, so two programs could be listening on the "same" port number (but on different addresses). Also, there might be any number of reasons why a particular program may not be permitted to listen on a particular port, including local firewall policies, or ACLs, or any other possible reason.

Assuming you want to listen for incoming connections, just try to bind() to the address and port of interest, and you will either get an error or not depending on whether your application can listen on that port.

Greg Hewgill
For a single port (or a few) this is easy, convenient and fast enough. To obtain a list of free ports (for whatever he wants it?) would require doing this 64K times, which I don't see happening in reasonable time.
Carl Smotricz
That's true. I was more addressing the second half of the question, since the first part seemed to be a possible means to answer the second part.
Greg Hewgill