简体   繁体   English

UDP套接字的发件人IP /端口

[英]Sender IP/Port for UDP Socket

Is it possible to obtain the sender IP and (dynamically obtained) port with C sockets? 是否可以使用C套接字获取发送者IP和(动态获得的)端口? 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! 任何和所有帮助表示感谢,谢谢!

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. 通常,您可以使用getsockname(2)获取本地地址/端口信息,但是这里还没有-套接字没有连接并且什么也没发送。 If this is a simple UDP client - consider using connected UDP sockets - you'd be able to see local IP/port right after the connect(2) . 如果这是一个简单的UDP客户端-考虑使用已连接的UDP套接字 -您可以在connect(2)之后立即看到本地IP /端口。

For non-connected UDP sockets, there's no way to get the local address. 对于未连接的UDP套接字,无法获取本地地址。 You can of course get the remote address by using recvfrom instead of read / recv to read packets. 您当然可以通过使用recvfrom而不是read / recv来读取数据包来获取远程地址。 If you'll only be communicating with a single server, just go ahead and use connect . 如果您只与单个服务器通信,则继续并使用connect If you need to communicate with more than one server, you can probably just make a dummy connect (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. 如果您需要与多个服务器进行通信,则可以仅在其中一个服务器上进行虚拟connect (在新的套接字上)以获取您的本地地址,但是也可以(如果主机使用非平凡的路由)连接到不同的远程主机将导致不同的本地地址。 This can even happen in a fairly trivial environment if you connect both to localhost ( 127.0.0.1 ) and remote servers. 如果同时连接到localhost127.0.0.1 )和远程服务器,则在相当琐碎的环境中甚至可能发生这种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM