Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
877 views
in Technique[技术] by (71.8m points)

c - 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
", 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...