Sender IP/Port for UDP Socket

半腔热情 提交于 2019-11-28 10:35:46

问题


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!


回答1:


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 the connect(2).




回答2:


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 of read/recv to read packets. If you'll only be communicating with a single server, just go ahead and use 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. This can even happen in a fairly trivial environment if you connect both to localhost (127.0.0.1) and remote servers.



来源:https://stackoverflow.com/questions/4129220/sender-ip-port-for-udp-socket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!