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

孤街浪徒 提交于 2019-12-06 02:55:53

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.

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;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!