如何从 UDP 套接字获取 IP 信息 (Windows C++)?
我试图找到我的UDP套接字绑定到的IP地址(假设我不想使用其他方法来查找计算机的IP地址)。这怎么能做到呢?下面的代码适用于端口号,但始终返回 0.0.0.0 作为地址:
struct sockaddr_in sin;
int addrlen = sizeof(sin);
if(getsockname(clientSock, (struct sockaddr *)&sin, &addrlen) == 0 &&
sin.sin_family == AF_INET &&
addrlen == sizeof(sin)){
printf("RETURNING ADDR: %s: len = %d\n", inet_ntoa(sin.sin_addr),
strlen(inet_ntoa(sin.sin_addr)));
}
使用以下代码绑定套接字:
sockaddr_in local;
local.sin_family = AF_INET;
local.sin_addr.s_addr = INADDR_ANY;//inet_addr("127.0.0.1");
local.sin_port = 0; //assign given port
result = bind(clientSock, (sockaddr*)&local, sizeof(local));
感谢您提供的所有帮助。我很感谢您的时间!
I tried to find the IP address that my UDP socket is bound to (assuming I don't want to use another method to find the computer's IP address). How can this be done? The code below works for the PORT number, but always returns 0.0.0.0 for the address:
struct sockaddr_in sin;
int addrlen = sizeof(sin);
if(getsockname(clientSock, (struct sockaddr *)&sin, &addrlen) == 0 &&
sin.sin_family == AF_INET &&
addrlen == sizeof(sin)){
printf("RETURNING ADDR: %s: len = %d\n", inet_ntoa(sin.sin_addr),
strlen(inet_ntoa(sin.sin_addr)));
}
The socket was bound using the following code:
sockaddr_in local;
local.sin_family = AF_INET;
local.sin_addr.s_addr = INADDR_ANY;//inet_addr("127.0.0.1");
local.sin_port = 0; //assign given port
result = bind(clientSock, (sockaddr*)&local, sizeof(local));
Thank you for any and all help. I appreciate your time!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
0.0.0.0
是INADDR_ANY
,这意味着套接字绑定到主机上的所有本地地址,而不仅仅是一个地址。您正在请求一个地址,但您并未绑定到一个地址,因此getsockname()
无法报告特定地址。如果您希望
getsockname()
报告特定地址,则必须bind()
到该特定地址。因此,请使用GetAdaptersAddresses
< /a> 枚举本地主机上的所有接口,并为每个地址bind()
一个单独的套接字,而不是在单个地址上绑定INADDR_ANY
插座。否则,您可以
bind()
将单个套接字绑定到INADDR_ANY
,然后使用WSARecvMsg()
(而不是recv()
,recvfrom()
或WSARecvFrom()
) 读取传入数据包。如果您使用setsockopt()
。0.0.0.0
isINADDR_ANY
, meaning the socket is bound to all local addresses on the host, not just one address. You are asking for one address, but you are not bound to one address, sogetsockname()
cannot report a specific address.If you want
getsockname()
to report a specific address, you have tobind()
to that specific address. So useGetAdaptersAddresses
to enumerate all interfaces on the local host andbind()
a separate socket to each address, instead of bindingINADDR_ANY
on a single socket.Otherwise, you can
bind()
a single socket toINADDR_ANY
, and then useWSARecvMsg()
(instead ofrecv()
,recvfrom()
, orWSARecvFrom()
) to read the incoming packets.WSARecvMsg()
can report details about each packet's arrival interface and destination address, if you enable the appropriate options withsetsockopt()
.