Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * @brief Sends an ethernet frame
- */
- #include <arpa/inet.h>
- #include <linux/if_packet.h>
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- #include <sys/ioctl.h>
- #include <sys/socket.h>
- #include <net/if.h>
- #include <netinet/ether.h>
- #include <linux/ip.h>
- #define pexit(x) \
- do { \
- perror(x); \
- exit(EXIT_FAILURE); \
- } while (0)
- static char buf[BUFSIZ];
- void parse_mac(char *hwstr, uint8_t mac[6])
- {
- char *ptr;
- int i;
- for (i = 0, ptr = hwstr; i < 6; i++) {
- mac[i] = strtol(ptr, NULL, 16);
- ptr = strchr(ptr, ':');
- if (!ptr)
- return;
- ptr++;
- }
- }
- void print_mac(uint8_t mac[6])
- {
- int i;
- printf("MAC: ");
- for (i = 0; i < 6; i++)
- printf("%02X:", mac[i]);
- putchar('\n');
- }
- int main(int argc, char **argv)
- {
- int sock;
- struct ifreq ifr;
- struct ether_header *eh = (struct ether_header *) buf;
- struct sockaddr_ll sll;
- int len = 0;
- int i = 0;
- int ifidx;
- int n;
- if (argc != 4) {
- fprintf(stderr, "Usage: %s SRCIF DSTHW DATA\n", argv[0]);
- exit(EXIT_FAILURE);
- }
- if ((sock = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL))) == -1)
- pexit("socket");
- memset(&ifr, '\0', sizeof(ifr));
- strncpy(ifr.ifr_name, argv[1], IFNAMSIZ - 1);
- if (ioctl(sock, SIOCGIFINDEX, &ifr) < 0)
- pexit("SIOCGIFINDEX");
- printf("Source index: %d\n", ifr.ifr_ifindex);
- ifidx = ifr.ifr_ifindex;
- if (ioctl(sock, SIOCGIFHWADDR, &ifr) < 0)
- pexit("SIOCGIFHWADDR");
- /* Set Destination and Source */
- memcpy(eh->ether_shost, ifr.ifr_hwaddr.sa_data, 6);
- printf("Source ");
- print_mac(eh->ether_shost);
- parse_mac(argv[2], eh->ether_dhost);
- printf("Destination ");
- print_mac(eh->ether_dhost);
- eh->ether_type = htons(ETH_P_ALL);
- len += sizeof(struct ether_header);
- strncpy(&buf[len], argv[3], strlen(argv[3]));
- len += strlen(argv[3]);
- printf("LENGHT: %d\n", len);
- memset(&sll, '\0', sizeof(sll));
- sll.sll_ifindex = ifidx;
- sll.sll_halen = ETH_ALEN;
- sll.sll_family = AF_PACKET;
- parse_mac(argv[2], (uint8_t *)&sll.sll_addr);
- len += sizeof(struct ether_header);
- if (sendto(sock, buf, ETH_ALEN, 0, (struct sockaddr *)&sll, sizeof(sll)) < 0)
- perror("send");
- if ((n = recvfrom(sock, buf, BUFSIZ, 0, NULL, NULL)) < 0)
- perror("recvfrom");
- printf("Received %d bytes from %02x:%02x:%02x:%02x:%02x:%02x\n",
- n,
- eh->ether_dhost[0],
- eh->ether_dhost[1],
- eh->ether_dhost[2],
- eh->ether_dhost[3],
- eh->ether_dhost[4],
- eh->ether_dhost[5]);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement