如何在TCP层上检查该套接字是否处于活动状态?

时间:2014-01-09 15:07:46

标签: c sockets tcp port tcpclient

typedef unsigned int uint16;
SOCKET s, new_socket;
uint16 port =18001;

    void CreateSocket()
    {
            WSADATA wsa;
            struct sockaddr_in server;  // creating a socket address structure: structure contains ip address and port number


                printf("Initializing Winsock\n");
            if(WSAStartup(MAKEWORD(2,2), &wsa)!=0)
            {
                printf("Failed Error Code: %d", WSAGetLastError());
                return -1;
            }
            printf("Initialised\n");


            //CREATING a SOCKET

            if ((s = socket(AF_INET, SOCK_STREAM, 0)) == -1)
            {
                printf("Could not Create Socket\n");
                //return 0;
            }
            printf("Socket Created\n");

            server.sin_addr.s_addr = inet_addr("192.168.0.1");
            server.sin_family = AF_INET;     
            server.sin_port = htons(port); 
//Binding between the socket and ip address

    if(bind (s, (struct sockaddr *) &server, sizeof(server)) == SOCKET_ERROR)
    {
        printf("Bind failed with error code: %d", WSAGetLastError());
    }
    puts("Bind Done");


    //Listen to incoming connections
    listen(s, 3);


    //Accepting the incoming connection
         new_socket = accept(s, NULL, NULL);

       if (new_socket == INVALID_SOCKET)
       {
    printf(L"accept failed with error: %ld\n", WSAGetLastError());
    closesocket(new_socket);
    WSACleanup();
    return 1;
} 
       else
    printf("Client connected.\n");

字关闭(多个);

        }

int main()
{
CreateSocket();

return 0;
}

这是针对TCP的。 我通过上面的ip地址和端口号从MASTER接收连接,所以我创建了一个带有端口号和ip地址的套接字。但是如何检查套接字是否处于活动状态?如何检查上面的套接字代码是否有效(它没有显示任何错误)。我在MASTER方面收到错误说: 连接事件检查失败(WSAGetLastError()) 任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

您的套接字与地址之间没有任何关联,您永远不会server s中的地址{{1}}。

当然,这是您的客户端无法连接的原因,因为套接字不会使用预期的端口。我假设您在其他地方调用bind()等等,实际上也使套接字接受传入连接。