Lately I’ve been writing some code to send packets to a specific MAC address from a specific interface. I’m sure this will come in handy again so here is how it goes:
Includes:
(might not need all of these)
#include <netinet/in.h> #include <sys/socket.h> #include <arpa/inet.h> #include <net/if.h> #include <netinet/ip.h> #include <netinet/udp.h> #include <netinet/ether.h> #include <linux/if_packet.h>
Open the raw socket:
int sockfd; ... /* Open RAW socket to send on */ if ((sockfd = socket(AF_PACKET, SOCK_RAW, IPPROTO_RAW)) == -1) { perror("socket"); }
Get the index of the interface to send on:
struct ifreq if_idx; ... memset(&if_idx, 0, sizeof(struct ifreq)); strncpy(if_idx.ifr_name, "eth0", IFNAMSIZ-1); if (ioctl(sock, SIOCGIFINDEX, &if_idx) < 0) perror("SIOCGIFINDEX");
Get the MAC address of the interface to send on:
struct ifreq if_mac; ... memset(&if_mac, 0, sizeof(struct ifreq)); strncpy(if_mac.ifr_name, "eth0", IFNAMSIZ-1); if (ioctl(sock, SIOCGIFHWADDR, &if_mac) < 0) perror("SIOCGIFHWADDR");
Get the IP address of the interface to send on:
struct ifreq if_ip; …
View original post 437 more words