It depends slightly on exactly what you're trying to test.
Using bind()
in the way that joelc suggested will tell you if the port is open on any interface on your machine. Although to be thorough, you should not only be checking the return value from bind()
, but also checking errno == EADDRINUSE
.
ie. (modification of joelc's code)
if(bind(socket, (struct sockaddr *)&sin,sizeof(struct sockaddr_in) ) == -1)
{
if( errno == EADDRINUSE )
{
// handle port already open case
}
else
{
// handle other errors
}
}
By changing the address used in the line: eg.
sin.sin_addr.s_addr = inet_addr("192.168.1.1");
...you can test whether a port is available on a specific interface.
Be aware though that this isn't a perfect test for port state. If another process had the port open and was terminated before it gracefully closed the port (ie. before calling close()
on the socket) then you will usually get the same EADDRINUSE
error.
(depending on whether the SO_REUSEADDR option had been set on the socket)
(side note: unless your test application is running with sufficient privileges you won't be able to bind() to any ports below 1024)
As Anonymous suggested, you can also have a look at netstat
. This will give you all of the same information that you can get by repeatedly calling bind()
much more quickly and without any of the side effects (like it doesn't have to actually bind to the ports, which would make them unusable to any other processes).
Just calling netstat -a --numeric-ports -t
and analysing the output should give you everything that you're after.
A comment on moogs suggestion though - calling telnet on each port will only tell you if a socket is listening on that port - not whether it's actually open.