본문 바로가기
[ ★ ]Study/Network

Ethernet 헤더 만들기

by nroses-taek 2017. 7. 20.

Make Ethernet Header
이더넷 헤더 만들기

<기초 지식>

(이더넷 프로토콜)

(이더넷 매크로)

리눅스 환경 "/usr/include/net/ethernet.h"에 정의되어 있습니다.

 

Ethernet.h

 
#ifndef ETHERNET_H
#define ETHERNET_H

#include <stdint.h>

#define ETHERTYPE_IP    0x0800            //IPv4
#define ETHERTYPE_ARP    0x0806        //ARP
#define ETHERTYPE_REVARP    0x8035    //RARP
#define ETHERTYPE_IPV6    0x86dd        //IPv6

struct ether_header{
    uint8_t ether_dhost[6];
    uint8_t ether_shost[6];
    uint16_t ether_type;
}
__attribute__((__packed__));

void dump_ether_header(struct ether_header *ether_header);

#endif

destination addr , source ether addr ... 이 구조체로 선언되어 있다.

18행에서는 이더넷 헤더 출력을 위해 function prototype을 선언시켜 놓았다.

 

Ethernet.c

#include <stdio.h>

#include "ethernet.h"

void dump_ether_header(struct ether_header *ether_header){
    
    unsigned char *smac = ether_header->ether_shost;
    unsigned char *dmac = ether_header->ether_dhost;

    printf("[ETHERNET] "\ 
                    "%02x:%02x:%02x:%02x:%02x:%02x ->"\
                    "%02x:%02x:%02x:%02x:%02x:%02x\n",
                    smac[0], smac[1], smac[2], smac[3], smac[4], smac[5],
                    dmac[0], dmac[1], dmac[2], dmac[3], dmac[4], dmac[5]);
}
 

헤더파일에서 선언해놓고 구현을 Ethernet.c 파일에 해 놓았다. 또한 그 내용은 smac, dmac을 출력하는 간단한 과정이다.

 

Excute.c

#include <stdio.h>
#include <string.h>
#include <netinet/in.h>

#include "ethernet.h"

int main(void){
    struct ether_header ether_header;
    int i;

    ether_header.ether_type = htons(ETHERTYPE_IP);

    for(i=0; i<6; i += 1){
        ether_header.ether_dhost[i] = i;
    }

    for(i=0; i<6; i+=1){
        ether_header.ether_shost[i] = i +0x10;
    }

    printf("ether_header : %lu\n", (unsigned long)sizeof(struct ether_header));

    dump_ether_header(&ether_header);

    return 0;
}
 

for을 통해 간단히 값들을 넣어주었다.

 

RAW 소켓 연습.

댓글