How to get sender UDP port in C?

I have the following typical code in C for 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 of the above code works, but now I need to find out the sender udp port, is there a structure or system call that I can use to get this information when I receive the udp packet?

thanks

+5
source share
5 answers

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

The sender 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);

: Beej Guide to Network Programming MSDN

+11

recvfrom() (struct sockaddr *).

EDIT: -

struct sockaddr_in client;

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

client.sin_port .

+6

UDP . , , .

+1

struct sockaddr_in, sin_port - .

0

, , sockaddr_in, , , - , .

0

All Articles