Reputation: 1326
I want to write a application which should receive all incoming packets irrespective whether the packet is destined to my machine and suppose to be forwarded or the packet is destined to local host.
I have open a AF_PACKET
socket for this purpose. But, since, my machine has multiple interface, how can I bind the socket to multiple interfaces to capture all incoming packets from any interface.
The following code segment bind my socket to only one interface. How can I modify it to bind with all interfaces. Also, How can I bind to some set of interfaces, can I call bind on same socket multiple times to bind with different interfaces ?
strncpy ((char *) ifr.ifr_name, interface, IFNAMSIZ);
ioctl (sock, SIOCGIFINDEX, &ifr);
sll.sll_family = AF_PACKET;
sll.sll_ifindex = ifr.ifr_ifindex;
sll.sll_protocol = htons (ETH_P_IP);
if(bind ( sock, (struct sockaddr *) &sll, sizeof (sll) ) )
{
perror("Bind");
exit(1);
}
//len = recvfrom(sock, rec_buff, 5000,0,(struct sockaddr *)&client_addr, &addr_len);
len = read(sock, rec_buff, 5000);
Upvotes: 1
Views: 4033
Reputation: 8563
Doing man socket
gives:
AF_PACKET Low level packet interface packet(7)
man 7 packet
gives:
By default all packets of the specified protocol type are passed to a packet socket. To get packets only from a specific interface use bind(2) specifying an address in a struct sockaddr_ll to bind the packet socket to an interface. Only the sll_protocol and the sll_ifindex address fields are used for purposes of binding.
So, at least according to the man page, if you want to capture from all interfaces, simply do not bind the socket.
A single socket cannot be bound to more than one interface. If you want to get a subset, create multiple sockets and bind them all. Use select
or one of it's better siblings (epoll_pwait
on Linux) to wait for any of them to receive a packet.
Upvotes: 3