tcp,先bind一个任意端口,sockaddr_in的sin_port 设0.
bind成功之后,connect。
在connect之后,通过getsockname可以得到实际的端口号。
但如果在connect之前,通过getsockname得到的端口却是0。实际端口号似乎是在connect的时候确定的。
在sockaddr_in的sin_port 设0的前提下,有办法在connect之前得知(或指定)实际端口号吗?分不够,只有20分。请见谅。

解决方案 »

  1.   

    The getsockname function does not always return information about the host address when the socket has been bound to an unspecified address, unless the socket has been connected with connect or accept (for example, using ADDR_ANY). A Windows Sockets application must not assume that the address will be specified unless the socket is connected. The address that will be used for the socket is unknown unless the socket is connected when used in a multihomed host. If the socket is using a connectionless protocol, the address may not be available until I/O occurs on the socket.
      

  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.IP地址不一定能得到,但可以得到实际端口。