问题
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
回答1:
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, (struct sockaddr *)&client, (socklen_t *)&len);
int port = ntohs(client.sin_port);
References: Beej's Guide to Network Programming and MSDN
回答2:
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.
回答3:
UDP sender port would be transient. I don't think you could use that for anything other than for reporting.
回答4:
The fifth argument can be cast to struct sockaddr_in
, and there sin_port
is the remote port number.
回答5:
Casting the client to sockaddr_in solves my problem.
回答6:
Yes! Remember the ntohs() above all! It wasn't until I used the programmer's calculator that I realized it WAS stored as BigEndian 15B3, not the presumably ephemeral port B315!
来源:https://stackoverflow.com/questions/702451/how-do-i-get-senders-udp-port-in-c