怎么获取socket 自动绑定的端口号

糊涂男人 2008-01-21 09:53:32
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 当前用的端口是多少?
...全文
372 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
僵哥 2008-01-21
  • 打赏
  • 举报
回复
下面是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.
僵哥 2008-01-21
  • 打赏
  • 举报
回复
抱歉发错了,应该是getsockname.
糊涂男人 2008-01-21
  • 打赏
  • 举报
回复
顶一下
僵哥 2008-01-21
  • 打赏
  • 举报
回复
GetPeerName

18,356

社区成员

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

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