3

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

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

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

例如端口 21111(netstat 的输出)-> 我的函数无法识别该端口不是空闲的

TCP    0.0.0.0:21111          xxxxDUMMYxxxx:0       LISTENING

谢谢

4

2 回答 2

4

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

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

于 2012-11-09T09:25:27.613 回答
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;
    }
}
于 2018-01-22T05:11:26.533 回答