Check if TCP port is available (not listening or connected)

leon22 picture leon22 · Nov 9, 2012 · Viewed 14.3k times · Source

I use following code to check if a port is available or not:

bool ClassA::CheckPortTCP(short int dwPort , char *ipAddressStr)  
{  
    struct sockaddr_in client;         
    int sock;   

    client.sin_family = AF_INET;  
    client.sin_port = htons(dwPort);  
    client.sin_addr.S_un.S_addr = inet_addr(ipAddressStr);      

    sock = (int) socket(AF_INET, SOCK_STREAM, 0);  

    int result = connect(sock, (struct sockaddr *) &client,sizeof(client)); 

    // change to result == 0 -> failure in writing code too quick ;-)
    if (result = 0) return true; // port is active and used
    else return false; 
}  

The problem is if the port is opened but not connected the check failed! How can I easily examine that the port is available (not listening, not connected)?

e.g. port 21111 (output of netstat) -> my function doesn't recognize that the port is not free

TCP    0.0.0.0:21111          xxxxDUMMYxxxx:0       LISTENING

Thx

Answer

Some programmer dude picture Some programmer dude · Nov 9, 2012

You have two errors: The first is that in the if statement you assign zero to result. The other is that connect returns -1 on failure to connect, and a non-negative value if it manages to connect.

There is also a problem that if you manage to connect, you don't close that connection.