tags:

views:

772

answers:

5

I have the following typical code in C under Linux to get UDP data:

sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
mysock.sin_family = AF_INET;
mysock.sin_addr.s_addr = INADDR_ANY;
mysock.sin_port = my_port;
bind(sock, &mysock, sizeof(mysock);
recvfrom(sock, buf, PKTSZ, 0, &client, len);

All the above code works, but now I have a need to find out the sender's udp port, is there a structure or system call I can use to retrieve such info when I receive a udp packet ?

thanks

+3  A: 

recvfrom() is supposed to return that to you in the fifth argument (struct sockaddr*).

EDIT: Use something like this

struct sockaddr_in client;

recvfrom(... (struct sockaddr*)&client ...);

client.sin_port should be the sender's port.

sigjuice
I look at that argument before but the struct sockaddr does not have any sender's udp port info, unless it is embedded inside the sa_data.
+1  A: 

UDP sender port would be transient. I don't think you could use that for anything other than for reporting.

Indeera
I might not make myself clear, I need to know the sender's udp port so I can send data back immediately, so it's ok to be transient.
you can only send data back to a listening udp socket. It's unlikely that your sender socket is also a listening socket. If you need this behaviour, you need to have listening udp sockets on both sides.
Indeera
+1  A: 

recvfrom(sock, buf, PKTSZ, 0, &client, len);

The senders socket address is stored in the client variable of your code. To access the senders port use sockaddr_in instead of sockaddr. Example:

sockaddr_in client;
int len = sizeof(client);
recvfrom(sock, buf, PKTSZ, 0, reinterpret_cast<sockaddr*>(&client), &len);
int port = ntohs(client.sin_port);

References: Beej's Guide to Network Programming and MSDN

reinterpret_cast does not belong here. The OP asked for C (not C++)
sigjuice
ditto - downvote until the cast is corrected
Alnitak
A: 

The fifth argument can be cast to struct sockaddr_in, and there sin_port is the remote port number.

E Dominique
A: 

Thanks guys, casting the client to sockaddr_in solves my problem and deeply appreciate for the quick response, hopefully someday I can contribute when I get better with this stuff.

Contribute a little by picking a correct answer :)
dwc