2016-12-11 9 views
1

나는이 코드 우연의 일치주의 :코드의 명확하지 않은 목적은 무엇입니까? 나는 리눅스 및 튜토리얼 동안 원시 소켓 프로그래밍에 대해 배우고

struct ipheader { 
unsigned char  iph_ihl:5, iph_ver:4; //<--------------These 
unsigned char  iph_tos; 
unsigned short int iph_len; 
unsigned short int iph_ident; 
unsigned char  iph_flag; 
unsigned short int iph_offset; 
unsigned char  iph_ttl; 
unsigned char  iph_protocol; 
unsigned short int iph_chksum; 
unsigned int  iph_sourceip; 
unsigned int  iph_destip; 
}; 

iph_ver 4 될 IP 버전을 보유, 그리고 iph_ihl이 설정됩니다 헤더 길이를 보유하고 헤더 길이는 4 바이트 워드로 기술되므로 실제 헤더 길이는 5 × 4 = 20 바이트가된다. 20 바이트가 최소 길이입니다.과 iph_ihl으로 설정된이 구조의 비트 필드가 IPv4 일 것이고 IP 헤더의 길이가 20 바이트가되기 때문에이 구조의 비트 필드가 구체적으로 4와 5인지 궁금합니다. 그러나 나는 그들의 비트 필드가 그들의 가치에 어떤 영향이나 상관 관계가 있을지 확신 할 수 없다. 모든 설명은 크게 감사하겠습니다. 코드

링크 : http://www.tenouk.com/Module43a.html

+2

비트 필드입니다. –

+0

@VladfromMoscow 그러나 비트 필드는 비트 단위로 크기를 결정하지 않습니까? 그들은 데이터의 실제 가치를 결정하지 못하고 단지 얼마나 많은 공간이 있는지를 결정합니다. 또는 비트 필드에 대한 근본적인 무언가 및/또는 버전 및 헤더 길이가 IP 헤더에서 어떻게 작동합니까? –

+1

이상하게도 IHL은 4 비트 필드로되어 있습니다. – harold

답변

3

이 튜토리얼의 코드 조각은 실제로 잘못입니다!

/* 
* Structure of an internet header, naked of options. 
* 
* We declare ip_len and ip_off to be short, rather than u_short 
* pragmatically since otherwise unsigned comparisons can result 
* against negative integers quite easily, and fail in subtle ways. 
*/ 
struct ip { 
#if BYTE_ORDER == LITTLE_ENDIAN 
    u_char ip_hl:4,  /* header length */ 
      ip_v:4;   /* version */ 
#endif 
#if BYTE_ORDER == BIG_ENDIAN 
    u_char ip_v:4,   /* version */ 
      ip_hl:4;  /* header length */ 
#endif 
    u_char ip_tos;   /* type of service */ 
    short ip_len;   /* total length */ 
    u_short ip_id;   /* identification */ 
    short ip_off;   /* fragment offset field */ 
#define IP_DF 0x4000  /* dont fragment flag */ 
#define IP_MF 0x2000  /* more fragments flag */ 
    u_char ip_ttl;   /* time to live */ 
    u_char ip_p;   /* protocol */ 
    u_short ip_sum;   /* checksum */ 
    struct in_addr ip_src,ip_dst; /* source and dest address */ 
}; 

당신이 볼 수 있듯이, 두 ip_hlip_v 4 비트 폭 비트 필드입니다 : 여기

는 IP 패킷 헤더에 대한 올바른 정의입니다. 필드의 실제 이름은 중요하지 않으며 패킷 헤더의 위치 만 다릅니다.

컴파일러는 엔디안에 따라 비트 필드를 다르게 할당하기 때문에 플랫폼에 따라 다른 순서로 정의됩니다. 이 동작은 실제로 C 표준에 지정되어 있지 않지만 플랫폼간에 일관된 것으로 보입니다.

+0

대단히 감사합니다! 유사한 사건을 피하기 위해 새로운 튜토리얼을 찾을 것입니다. –