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