当TCP客户端成功的连接到服务器时,服务器怎样得到每条连接使用的端口号?

解决方案 »

  1.   

    The getpeername function retrieves the name of the peer to which a socket is connected.
    int getpeername(
      SOCKET s,
      struct sockaddr* name,
      int* namelen
    );Res
    The getpeername function retrieves the name of the peer connected to the socket s and stores it in the a SOCKADDR structure identified by name. The getpeername function can be used only on a connected socket. For datagram sockets, only the name of a peer specified in a previous connect call will be returned—any name specified by a previous sendto call will not be returned by getpeername.On call, the namelen parameter contains the size of the name buffer, in bytes. On return, the namelen parameter contains the actual size in bytes of the name returned.
      

  2.   

    CString ip;
    unsigned int port;
    psock->GetPeerName(ip,port);
      

  3.   

    my sample:
    struct in_addr addr;
    unsigned short port;
    SOCKADDR_IN m_sockServerAddr;Client = accept(ServerSocket,(LPSOCKADDR)&m_sockServerAddr,0);
    port = ntohs(m_sockServerAddr.sin_port);
    memcpy(&addr, &(m_sockServerAddr.sin_addr), sizeof(struct in_addr));printf("IP: %s\n", inet_ntoa(addr));
    printf("Port: %d\n", port);