Maicake
Maicake

Reputation: 1126

Problem in the initialization of src dst fields in the ethernet header

GOAL: craft a packet from zero and send it through a socket

PROBLEM: currently I'm not sure if the ethernet header structure has the right mac address because the print shows just messed symbols. Am I using the wrong format specifiers or there is another problem?

int main(){

        const char IF[] = "wlp3s0"; // modify to change interface
        int sockfd, ifindex;
        struct ifreq ifr;
        size_t if_name_len;
        char buf[BUF_SIZE];
        struct ether_header *eh = (struct ether_header *) buf;
        struct iphdr *iph = (struct iphdr *) (buf + sizeof(struct ether_header));

        // create raw socket to send/receive ethernet frames that transport ip packet
        if ((sockfd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_IP))) == -1) {
            perror("socket");
        }

        // get interface name length
        if_name_len = strlen(IF);
        if(if_name_len < IF_NAMESIZE) {
                strncpy(ifr.ifr_name, IF, strlen(IF));
        }

        // get the interface index number
        if(ioctl(sockfd, SIOCGIFINDEX, &ifr) == -1){
                perror("ioctl");
        }
        ifindex = ifr.ifr_ifindex;

        // build ethernet header        
        const char dmac[] = {0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff};
        memcpy(eh->ether_dhost, dmac, ETHER_ADDR_LEN);
        printf("%s\n", eh->ether_dhost);

Upvotes: 0

Views: 153

Answers (1)

The printf call shows strange symbols, because you are using the wrong format specifier. There is no right format specifier to print a MAC address. You could print each part individually with %02hhx (i.e. use this 6 times).

The reason you get strange symbols is because you told printf to print a string. A string is a series of bytes where each byte is the ASCII code for a character, followed by a 0 byte to indicate the end of the string. printf will print ASCII code 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, and then it will keep going until it happens to find a 0 byte, possibly printing a bunch more characters too.

Upvotes: 2

Related Questions