SOCKET sock
sockaddr_in sin;
sin.sin_addr.S_un.S_addr = INADDR_ANY;
sin.sin_family = AF_INET;
sin.sin_port = 0; if (bind(sock, (struct sockaddr*)&sin, sizeof(sin)) < 0)
{
          throw Exception("bind error");
}
       怎么获取sock 当前用的端口是多少?

解决方案 »

  1.   

    抱歉发错了,应该是getsockname.
      

  2.   

    下面是MSDN有关bind的一段描述:
    For TCP/IP, if the port is specified as zero, the service provider assigns a unique port to the application with a value between 1024 and 5000. The application can use getsockname after calling bind to learn the address and the port that has been assigned to it. If the Internet address is equal to INADDR_ANY, getsockname cannot necessarily supply the address until the socket is connected, since several addresses can be valid if the host is multihomed. Binding to a specific port number other than port 0 is discouraged for client applications, since there is a danger of conflicting with another socket already using that port number.