Check if TCP port is available (not listening or connected)
15,107
Solution 1
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.
Solution 2
the line client.sin_addr.S_un.S_addr = inet_addr(ipAddressStr);
can not work for me. change it to:
bool CheckPortTCP(short int dwPort, char *ipAddressStr)
{
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != NO_ERROR) {
wprintf(L"WSAStartup function failed with error: %d\n", iResult);
return false;
}
struct sockaddr_in client;
int sock;
client.sin_family = AF_INET;
client.sin_port = htons(dwPort);
client.sin_addr.s_addr = inet_addr(ipAddressStr);
sock = (int)socket(AF_INET, SOCK_STREAM, 0);
if (sock == INVALID_SOCKET) {
wprintf(L"ERROR: Socket function failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return false;
}
printf("INFO: Checking Port : %s:%d\n", ipAddressStr, dwPort);
int result = connect(sock, (struct sockaddr *) &client, sizeof(client));
if (result == SOCKET_ERROR) {
printf("ERROR: %s", WSAGetLastError());
WSACleanup();
return false;
}
else
{
WSACleanup();
closesocket(sock);
return true;
}
}
Related videos on Youtube
Author by
leon22
Updated on September 16, 2022Comments
-
leon22 over 1 year
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
-
Damien_The_Unbeliever over 11 yearsHow will you be using this information? If it's to find an appropriate port and open it, the only sane way to do it is to open the port and react to errors at that time. Anything else has timing issues.
-
-
Ed Heal over 11 yearsTo prevent this error in future get into the habit of putting the constant first. i.e.
if (0 == result)
. If you make a mistake of using one equal sign the compiler will pick it up! -
leon22 over 11 yearsOMG! I forgot a simple equal! Thx