naydichev
naydichev

Reputation: 4700

Sender IP/Port for UDP Socket

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!

Upvotes: 1

Views: 3288

Answers (2)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215193

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.

Upvotes: 0

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84151

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

Upvotes: 3

Related Questions