Sender IP/Port for UDP Socket

后端 未结 2 1696
感动是毒
感动是毒 2020-12-22 00:42

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_f         


        
相关标签:
2条回答
  • 2020-12-22 01:33

    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).

    0 讨论(0)
  • 2020-12-22 01:42

    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.

    0 讨论(0)
提交回复
热议问题