인디노트

eth0 에서 recvfrom 함수로 읽어서 그대로 eth1 으로 write 함수로 전송 하는 C 코드 본문

개발 플랫폼 및 언어/네트워크 기술

eth0 에서 recvfrom 함수로 읽어서 그대로 eth1 으로 write 함수로 전송 하는 C 코드

인디개발자 2023. 4. 13. 16:44
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <net/ethernet.h>
#include <arpa/inet.h>
#include <net/if.h>

#define ETH_FRAME_LEN 1518

int main() {
    int sockfd_in = 0, sockfd_out = 0, ret = 0;
    char buffer[ETH_FRAME_LEN] = {0};
    struct sockaddr_ll dest = {0};

    // create socket for eth0
    sockfd_in = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
    if (sockfd_in == -1) {
        perror("socket");
        exit(EXIT_FAILURE);
    }

    // bind socket to eth0
    struct sockaddr_ll addr = {0};
    addr.sll_family = AF_PACKET;
    addr.sll_ifindex = if_nametoindex("eth0");
    if (addr.sll_ifindex == 0) {
        perror("if_nametoindex");
        exit(EXIT_FAILURE);
    }
    ret = bind(sockfd_in, (struct sockaddr*)&addr, sizeof(struct sockaddr_ll));
    if (ret == -1) {
        perror("bind");
        exit(EXIT_FAILURE);
    }

    // create socket for eth1
    sockfd_out = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
    if (sockfd_out == -1) {
        perror("socket");
        exit(EXIT_FAILURE);
    }

    // set destination address
    memset(&dest, 0, sizeof(struct sockaddr_ll));
    dest.sll_family = AF_PACKET;
    dest.sll_protocol = htons(ETH_P_ALL);
    dest.sll_ifindex = if_nametoindex("eth1");
    if (dest.sll_ifindex == 0) {
        perror("if_nametoindex");
        exit(EXIT_FAILURE);
    }

    // loop to receive and forward Ethernet frames
    while (1) {
        // receive Ethernet frame from eth0
        ret = recvfrom(sockfd_in, buffer, ETH_FRAME_LEN, 0, NULL, NULL);
        if (ret == -1) {
            perror("recvfrom");
            exit(EXIT_FAILURE);
        }

        // send Ethernet frame to eth1
        ret = write(sockfd_out, buffer, ret);
        if (ret == -1) {
            perror("write");
            exit(EXIT_FAILURE);
        }
    }

    // close sockets
    close(sockfd_in);
    close(sockfd_out);

    return 0;
}

이 코드에서는 recvfromwrite 함수를 사용하여 패킷을 읽고 쓰기를 수행합니다. bind 함수를 사용하여 소켓을 eth0 인터페이스에 바인딩하고, dest 구조체를 사용하여 소켓을 eth1 인터페이스로 설정합니다. 이 코드는 패킷을 수정하지 않고 그대로 전달합니다.

반응형
Comments