C – Socket address types from recvfrom() and AF_PACKET/PF_PACKET

Socket address types from recvfrom() and AF_PACKET/PF_PACKET… here is a solution to the problem.

Socket address types from recvfrom() and AF_PACKET/PF_PACKET

On two PCs, I’m opening a AF_PACKET/PF_PACKET socket, the original protocol.

sock = socket(AF_PACKET, SOCK_RAW, htons(PROTO_BULK))

(EDIT: PROTO_BULK is a dummy type, created by myself for this test. I don’t want it to infer the problem, but I could be wrong. )

The first PC sends packets to another PC in a standard send() fashion, and the other end receives the packet by:

recvfrom(sock, buffer, 1600, 0, (struct sockaddr*) &from, &fromlen);

My question now is: What is the data type in “from”? Here’s the example I received:

00 00 00 00 00 00 00 00 f8 cd a1 00 58 1d a1 00 94 60

In terms of length and content, it is neither like “struct sockaddr” nor “sockaddr_ll”. Any ideas?

I’m actually looking for an interface to receive packets. I can use the destination MAC in the packet and identify the interface from it, but it doesn’t work with broadcast packets.

I’m running the latest Linux kernel (I don’t want to investigate kernel source code!).

EDIT: My code is wrong. I didn’t initialize “fromlen” with the “from” buffer size, so I’m assuming there are some fake values out there and “recvfrom()” doesn’t do its job correctly. Thanks Ben Voigt for pointing out this bug in the comments below! Of course, I didn’t include this part of the error code in my question, because obviously such a simple code can’t have errors….

With the correct parameters, I get a correctly populated “struct sockaddr_ll”, including the interface number I’m looking for.

Solution

I am actually looking for the interface the packet was received on.

You should use recvmsg, which can access metadata such as the destination address of the packet (useful for multihomed systems) and, I think, interface.

The sender address you are viewing now will not tell you the interface. However, it is useful to use sendto to send reply packets.

Related Problems and Solutions