如何知道bind的任意端口实际是多少

samuelo 2011-04-08 08:15:15
tcp,先bind一个任意端口,sockaddr_in的sin_port 设0.
bind成功之后,connect。
在connect之后,通过getsockname可以得到实际的端口号。
但如果在connect之前,通过getsockname得到的端口却是0。

实际端口号似乎是在connect的时候确定的。
在sockaddr_in的sin_port 设0的前提下,有办法在connect之前得知(或指定)实际端口号吗?

分不够,只有20分。请见谅。
...全文
262 4 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
samuelo 2011-04-13
  • 打赏
  • 举报
回复
是我没有事先bind.....
Sou2012 2011-04-11
  • 打赏
  • 举报
回复
可以得到实际的端口。
GenuineCold 2011-04-11
  • 打赏
  • 举报
回复
摘一段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地址不一定能得到,但可以得到实际端口。
Eleven 2011-04-08
  • 打赏
  • 举报
回复
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.

18,363

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 网络编程
c++c语言开发语言 技术论坛(原bbs)
社区管理员
  • 网络编程
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧