UDP 套接字的发送者 IP/端口
是否可以使用C套接字获取发送者IP和(动态获取)端口?我有以下内容:
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
if ((rv = getaddrinfo(NULL, DATABASEPORT, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
exit(1);
}
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
perror("socket");
continue;
}
break;
}
这几乎是从指南中摘取的(尽管我有点明白了?)。但我无法确定我将使用哪些信息来查找客户数据。
感谢任何和所有的帮助,谢谢!
Is it possible to obtain the sender IP and (dynamically obtained) port with C sockets? I have the following:
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
if ((rv = getaddrinfo(NULL, DATABASEPORT, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
exit(1);
}
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
perror("socket");
continue;
}
break;
}
Which is pretty much taken from a guide (though I kind of get it?). But I'm having trouble identifying which information I would use to find out the client data.
Any and all help is appreciated, thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通常,您可以使用 获取本地地址/端口信息
getsockname(2)
,但这里还没有 - 套接字尚未连接,也没有发送任何内容。如果这是一个简单的 UDP 客户端 - 考虑使用 连接的 UDP 套接字 - 您将能够看到本地 IP /port 紧接在connect(2 )
。Generally you get the local address/port information with the
getsockname(2)
, but here you don't have it yet - the socket is not connected and nothing has been sent. If this is a simple UDP client - consider using connected UDP sockets - you'd be able to see local IP/port right after theconnect(2)
.对于非连接的 UDP 套接字,无法获取本地地址。当然,您可以通过使用
recvfrom
而不是read
/recv
来读取数据包来获取远程地址。如果您只与单个服务器通信,请继续使用connect
。如果您需要与多个服务器通信,您可能只需与其中一台服务器建立一个虚拟连接
(在新套接字上)即可获取您的本地地址,但这是可能的(如果主机使用非平凡的路由)连接到不同的远程主机将导致不同的本地地址。如果您同时连接到localhost
(127.0.0.1
) 和远程服务器,这种情况甚至可能发生在相当简单的环境中。For non-connected UDP sockets, there's no way to get the local address. You can of course get the remote address by using
recvfrom
instead ofread
/recv
to read packets. If you'll only be communicating with a single server, just go ahead and useconnect
. If you need to communicate with more than one server, you can probably just make a dummyconnect
(on a new socket) to one of the servers to get your local address, but it's possible (if the host uses nontrivial routing) that connecting to different remote hosts will result in different local addresses. This can even happen in a fairly trivial environment if you connect both tolocalhost
(127.0.0.1
) and remote servers.