인디노트

iphdr 의 check 계산 하는 C 코드 본문

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

iphdr 의 check 계산 하는 C 코드

인디개발자 2023. 4. 14. 15:01
#include <stdio.h>
#include <stdlib.h>
#include <netinet/ip.h>
#include <netinet/in.h>
#include <arpa/inet.h>

// IP 헤더의 체크섬 필드를 계산하는 함수
unsigned short calculate_ip_checksum(struct iphdr *ip_header) {
    unsigned int sum = 0;
    unsigned short checksum;

    // IP 헤더의 체크섬 필드는 0으로 초기화
    ip_header->check = 0;

    // IP 헤더의 각 2바이트를 16비트 체크섬 값에 더함
    for (int i = 0; i < sizeof(struct iphdr) / 2; i++) {
        sum += *((unsigned short*)ip_header + i);
    }

    // 체크섬 계산 결과에 carry를 전파하는 부분을 처리
    while (sum >> 16) {
        sum = (sum & 0xFFFF) + (sum >> 16);
    }

    checksum = ~sum;  // 1의 보수를 취함
    return checksum;
}

int main() {
    struct iphdr ip_header;
    ip_header.ihl = 5;  // IP 헤더의 길이
    ip_header.version = 4;  // IP 프로토콜 버전
    ip_header.tos = 0;  // 서비스 유형
    ip_header.tot_len = htons(sizeof(struct iphdr));  // 전체 IP 패킷 길이
    ip_header.id = 0;  // 패킷 식별자
    ip_header.frag_off = 0;  // 프래그먼트 옵션
    ip_header.ttl = 64;  // 패킷의 수명
    ip_header.protocol = IPPROTO_TCP;  // 상위 프로토콜
    ip_header.saddr = inet_addr("192.168.0.1");  // 송신지 IP 주소
    ip_header.daddr = inet_addr("192.168.0.2");  // 수신지 IP 주소

    // IP 헤더의 체크섬을 계산해서 채움
    ip_header.check = calculate_ip_checksum(&ip_header);

    return 0;
}

이 코드에서는 calculate_ip_checksum() 함수가 IP 헤더의 체크섬 필드를 계산합니다. 이 함수는 IP 헤더 구조체를 입력으로 받아서, 구조체의 체크섬 필드를 0으로 초기화한 뒤에 IP 헤더의 각 2바이트를 16비트 체크섬 값에 더합니다. 그리고 체크섬 계산 결과에 carry를 전파하는 부분을 처리한 뒤에, 최종 체크섬 값을 구한 후에 1의 보수를 취해서 반환합니다.

반응형
Comments