0

我正在读取文件 /proc/net/tcp6 的内容

并试图将 ip6 的符号转换为 '0::1' 之类的

以前使用 ipv4 y 使用下一个方法。

struct sockaddr_in tmp_ip;
char ip_str[30];
char ipex[]='00000AF0'; /*read from the file /proc/net/tcp */
tmp_ip.sin_addr.s_addr=(int)strtoll(ipex,NULL,16);
inet_ntop(AF_INET,&tmp_ip.sin_addr,ip_str,60);
printf("ip=%s \n",ip_str);

但是对于 ipv6,/proc/net/tcp6 的内容更大(33 个十六进制字符),也许我需要使用 sockaddr_in6,但变量 sin6_addr.s6_addr 是一个数组,而不是单个 log unsigned int(如 sin_addr.s_addr)

所以在简历中。我试图通过这个

0000000000000000FFFF00001F00C80A

类似于

::ffff:10.200.0.31

编辑..

嗯,也许如果我将 ex 分解成 16 个 ex 数字并将数组输入 sin6_addr.s_addr。因为 1F00C80A = 10.200.0.31(通过 ntop 函数)

4

2 回答 2

1

您可以使用sscanf()直接将字符串转换为s6_addr数组的元素:

struct in6_addr tmp_ip;
char ip_str[128];
char ipex[]="0000000000000000FFFF00001F00C80A";

if (sscanf(ipex,
    "%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx",
    &tmp_ip.s6_addr[3], &tmp_ip.s6_addr[2], &tmp_ip.s6_addr[1], &tmp_ip.s6_addr[0],
    &tmp_ip.s6_addr[7], &tmp_ip.s6_addr[6], &tmp_ip.s6_addr[5], &tmp_ip.s6_addr[4],
    &tmp_ip.s6_addr[11], &tmp_ip.s6_addr[10], &tmp_ip.s6_addr[9], &tmp_ip.s6_addr[8],
    &tmp_ip.s6_addr[15], &tmp_ip.s6_addr[14], &tmp_ip.s6_addr[13], &tmp_ip.s6_addr[12]) == 16)
{
    inet_ntop(AF_INET6, &tmp_ip, ip_str, sizeof ip_str);
    printf("ip=%s \n",ip_str);
}
于 2010-09-02T01:30:22.483 回答
0

谢谢。我结束了这样做。

cont_ip6=0; 
        cont=0;
        for(i=0;i<34;i++) {
                if (cont ==2) {
                        cont=0;
                        hex_section[2]='\0';
                                tmp_ip6.sin6_addr.s6_addr[cont_ip6]=strtol(hex_section,NULL,16);

                        cont_ip6++;
                }

                hex_section[cont]=ipex[i];
                cont++;

        }

然后 inet_ntop

我修好了它。

您需要反转每对十六进制数字。

::FFFF:10.200.0.31 以这样的数组结尾。

(最后一个元素)

FF     |FF    |   00   | 00  :  0A | C8   |   00 | 1F
255    |255   |   0    | 0   :  10 | 200  |   0  | 31

^       ^         ^      ^   :  ^     ^       ^     ^
|       |         |      |      |     |       |     |
|        ---------       |      |      -------      |
 ------------------------        -------------------

所以你需要交换这些(在每组数字中)

所以我这样做

tmptmp=0;
for (i=0;i<5;i++){
    tmptmp=tmp_ip6.sin6_addr.s6_addr[i*4+3];
    tmp_ip6.sin6_addr.s6_addr[i*4+3]=tmp_ip6.sin6_addr.s6_addr[i*4];
    tmp_ip6.sin6_addr.s6_addr[i*4]=tmptmp;

    tmptmp=tmp_ip6.sin6_addr.s6_addr[i*4+2];
    tmp_ip6.sin6_addr.s6_addr[i*4+2]=tmp_ip6.sin6_addr.s6_addr[i*4+1];
    tmp_ip6.sin6_addr.s6_addr[i*4+1]=tmptmp;
 }

这会交换集合,当您执行 inet_ntop 时,它会显示 ::FFFF:10.200.0.31

(我整天都在找这个 D:,我的头很痛)(对不起我的英语不好)

于 2010-09-02T02:25:12.377 回答