Sending Packet with VLAN tag using C Socket

7.7k views Asked by At

I am having a problem to understand VLAN tagging. I have already done changes in the /etc/network/interface file using this link I am using socket programming on Raspbian (Raspberry pi) using C language.

I tried 2 methods:

  1. The socket in C is

    s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);

When i send a ethernet packet from the raspberry pi using the above socket i only see the outgoing "arp" messages on the bus.

  1. s = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL))

But this creates an error "sendto failed: Invalid argument" during sending the packet, the code to send packet is:

struct sockaddr_in sin; 
sin.sin_family = AF_PACKET;
sin.sin_port = htons(30490);
sin.sin_addr.s_addr = inet_addr(destination ip address);


if(sendto(socket, data, iph->tot_len, 0, (struct sockaddr *)&sin, sizeof(sin)) < 0)
{ perror("Sendto failed"); }
else { printf("Packet send"); }

Could anyone help me with the information on how to attach a VLAN tag with every packet that is being send ? Or what i am doing wrong in above code ?

Is there a code which is already implemented for sending packets with VLAN?

(In my setup i am not using any router or switch)

1

There are 1 answers

1
Brian McFarland On

VLAN tagging occurs at the Ethernet header level, not the IP header. You need an AF_PACKET socket to get access to the ethernet header if trying to setup the VLAN tag manually. AFAIK, you cannot modify the ethernet header with an AF_INET socket.

If all you're trying to do is send VLAN tagged information over an otherwise "normal" socket and let the kernel generate the VLAN tag, you should just use the instructions shown in that link then open a normal socket that either:

  • binds to the local address of your VLAN virtual ethernet interface
  • or connects to an outside host that will go through the VLAN interface due to routing rules.