检查TCP端口是否可用(不是监听或连接)

时间:2012-11-09 09:18:49

标签: c++ network-programming port netstat

我使用以下代码检查端口是否可用:

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; 
}  

问题是如果端口已打开但未连接,则检查失败!如何轻松检查端口是否可用(不是监听,未连接)?

e.g。端口21111(netstat的输出) - >我的功能无法识别端口不是免费的

TCP    0.0.0.0:21111          xxxxDUMMYxxxx:0       LISTENING

THX

2 个答案:

答案 0 :(得分:4)

您有两个错误:第一个是if语句,您 0分配给result。另一个是connect在连接失败时返回-1,如果设法连接则返回非负值。

还有一个问题是,如果您设法连接,则不要关闭该连接。

答案 1 :(得分:1)

client.sin_addr.S_un.S_addr = inet_addr(ipAddressStr);行无法为我效劳。将其更改为:

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;
    }
}