2016-08-09 4 views
1

inet_ntop에서 잘못된 IPv6 문자열을 반환하는 것처럼 보입니다. 특히 "::"를 사용하여 0의 시퀀스를 삭제하려고하는 주소가있는 것 같습니다.inet_ntop 잘못된 IPv6 주소를 인쇄합니다.

다음은 코드입니다.

#include <stdio.h> 
#include <stdint.h> 
#include <arpa/inet.h> 

int main (void) 
{ 
    uint32_t ip[4] = {0xe0e0e0e0, 0xf0f0f0f0, 0x0, 0x1}; 
    char addr[INET6_ADDRSTRLEN] = ""; 

    inet_ntop(AF_INET6, ip, addr, INET6_ADDRSTRLEN); 
    printf("address = %s",addr); 
    return 0; 
} 

나는 이것을 실행할 때 다음과 같은 결과를 얻는다.

address = address = e0e0:e0e0:f0f0:f0f0::100:0 

이것은 상당히 잘못된 것처럼 보입니다.

address = e0e0:e0e0:f0f0:f0f0::1 

누구에게도이 문제가 무엇이 있는지 알고 있습니까?

감사합니다.

+3

[Mind the byte order!] (http://linux.die.net/man/3/htons) – Phillip

답변

4

메모는 바이트 순서에주의를 기울여야합니다. 또한 실제로 IP 주소로 struct in6_addr을 사용해야합니다. 다음은 초기화하는 예입니다 예상되는 출력을 제공 바이트의 순서로 : 여기의 x86 시스템에서 바이트 순서를 비교하는 간단한 예입니다 address = e0e0:e0e0:f0f0:f0f0::1

:에

#include <stdio.h> 
#include <stdint.h> 
#include <arpa/inet.h> 

int main (void) 
{ 
    const struct in6_addr ip = { 0xe0, 0xe0, 0xe0, 0xe0, 
           0xf0, 0xf0, 0xf0, 0xf0, 
           0x00, 0x00, 0x00, 0x00, 
           0x00, 0x00, 0x00, 0x01 }; 
    //const uint32_t ip[4] = { 0xe0e0e0e0, 0xf0f0f0f0, 0x0, 0x1 }; 
    char addr[INET6_ADDRSTRLEN]; 

    inet_ntop(AF_INET6, &ip, addr, INET6_ADDRSTRLEN); 
    printf("address = %s",addr); 
    return 0; 
} 

gcc main.c && ./a.out 결과를

address = e0e0:e0e0:f0f0:f0f0::1 
address bytes uint8 : E0 E0 E0 E0 F0 F0 F0 F0 00 00 00 00 00 00 00 01 
address bytes uint32: E0 E0 E0 E0 F0 F0 F0 F0 00 00 00 00 01 00 00 00 
,691 :
#include <stdio.h> 
#include <stdint.h> 
#include <arpa/inet.h> 

int main (void) 
{ 
    const struct in6_addr ip_uint8 = { 0xe0, 0xe0, 0xe0, 0xe0, 
             0xf0, 0xf0, 0xf0, 0xf0, 
             0x00, 0x00, 0x00, 0x00, 
             0x00, 0x00, 0x00, 0x01 }; 
    const uint32_t ip_uint32[4] = { 0xe0e0e0e0, 0xf0f0f0f0, 0x0, 0x1 }; 
    char addr[INET6_ADDRSTRLEN]; 

    inet_ntop(AF_INET6, &ip_uint8, addr, INET6_ADDRSTRLEN); 
    printf("address = %s\n",addr); 

    unsigned char* b = (unsigned char*)&ip_uint8; 
    printf("address bytes uint8 :"); 
    for(int i=0; i<16; i++) { 
     printf(" %2.2X", b[i]); 
    } 
    printf("\n"); 

    b = (unsigned char*)&ip_uint32; 
    printf("address bytes uint32:"); 
    for(int i=0; i<16; i++) { 
     printf(" %2.2X", b[i]); 
    } 
    printf("\n"); 

    return 0; 
} 

출력을 제공합니다

0xe0e0e0e0과 같은 반복적 인 바이트의 예제 단어는 이러한 종류의 문제를 디버깅 할 때 어떤 도움도주지 않습니다. 0x01020304은 잘못된 점을 훨씬 잘 이해할 수 있습니다.

3

이것은 네트워크 바이트 순서 문제입니다. 이 코드를 사용해보십시오.

char addr[INET6_ADDRSTRLEN] = ""; 
uint32_t ip[4] = {0xe0e0e0e0, 0xf0f0f0, 0x0, 0x1}; 
for(i=0;i<4;i++) 
{ 
    ip[i] = htonl(ip[i]); 
} 
inet_ntop(AF_INET6, ip, addr, INET6_ADDRSTRLEN); 
printf("address = %s\n",addr); 
관련 문제