Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 943
leon22 Avatar asked Nov 14 '25 14:11

leon22


1 Answers

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.

like image 179
Some programmer dude Avatar answered Nov 17 '25 10:11

Some programmer dude



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!