Reputation: 21
I have an application in Linux using C wherein I have created a socket to receive IPv6 UDP packet.
To receive the packet, I use recvmsg() since I need to retrieve the ifindex, which I can get from CMSG_DATA() with the option IPV6_PKTINFO. Now, I need the source port also to be read from the UDP packet. Is there way to get that too?
Upvotes: 2
Views: 3690
Reputation: 182684
Sure you can, recvmsg
looks like this:
ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags);
And struct msghdr
contains msg_name
and msg_namelen
:
struct msghdr {
void *msg_name; /* optional address */
socklen_t msg_namelen; /* size of address */
...
So you can do something like this for an IPv4 address:
struct sockaddr_in *src = msg->msg_name;
uint16_t port = ntohs(src->sin_port);
And adjust accordingly (sockaddr_in6
) for an IPv6 address.
I had completely overlooked getnameinfo
which R mentions in the comments. This function gets a struct sockaddr *
which means it doesn't depend on the address family. That function is way powerful but if all you want is the port, you're probably interested in NI_NUMERICSERV
.
Upvotes: 7