I have a embedded linux device that listens for UDP packets. The device has two ethernet interfaces so the packets can be retrieved on both interfaces. On certain UDP messages/packets I have to do do something specific for the interface that it was received on. So I need to detect which interface received the packet.
I have found posts and examples on Stackoverflow showing how to extract the destination IP from IP_PKTINFO
. This works fine if I test the interfaces one by one. With both interfaces connected and receiving the destination IP is the same.
I have noticed that the ifindex
is not the same, but I don't understand why the ipi_spec_dst
is the same when I clearly receive a packet on two different interfaces with two different IPs.
C/C++ Code responsible for extracting the destination IP:
ssize_t byteCount=recvmsg(f_socket, &message, 0);
if (byteCount==-1) {
printf("%s",strerror(errno));
}
for (struct cmsghdr *cmsg = CMSG_FIRSTHDR(&message);
cmsg != NULL;
cmsg = CMSG_NXTHDR(&message, cmsg))
{
if (cmsg->cmsg_level != IPPROTO_IP || cmsg->cmsg_type != IP_PKTINFO) continue;
struct in_pktinfo *pi = (struct in_pktinfo*) CMSG_DATA(cmsg);
char* destAddr = (char*) calloc(4, sizeof(char));
destAddr = inet_ntoa(pi->ipi_spec_dst);
std::cout << destAddr << " " << std::to_string(pi->ipi_ifindex) << std::endl;
}
Output eth0 connected:
172.20.55.9 4
172.20.55.9 4
172.20.55.9 4
...
Output eth0 connected:
200.0.0.101 6
200.0.0.101 6
200.0.0.101 6
...
Output eth0 and eth1 connected:
172.20.55.9 6
172.20.55.9 4
172.20.55.9 6
172.20.55.9 4
...
Expected output:
200.0.0.101 6
172.20.55.9 4
200.0.0.101 6
172.20.55.9 4
...
First of all, I'm not sure if this is expected or not, I do not think it is, but I might have not understood the documentation correctly.
I can supply more code if needed.
Code taken from:
Any and all help is greatly appreciated. Thank you.
-aln