expand an IPv6 address so I can print it to stdout

后端 未结 2 1536
耶瑟儿~
耶瑟儿~ 2020-12-31 16:00

I am using getifaddrs() and inet_ntop() to get the ip addresses on the system. When the system is set to IPv6 the address returned is in the shortened version (using :: for

2条回答
  •  借酒劲吻你
    2020-12-31 16:49

                #include
                #include 
                #include 
    
                struct in6_addrr
                {
                    unsigned char addr[16];
                };
    
                void ipv6_expander(const struct in6_addr * addr)
                {
                    char str[40];
                    sprintf(str,"%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x",
                    (int)addr->s6_addr[0], (int)addr->s6_addr[1],
                    (int)addr->s6_addr[2], (int)addr->s6_addr[3],
                    (int)addr->s6_addr[4], (int)addr->s6_addr[5],
                    (int)addr->s6_addr[6], (int)addr->s6_addr[7],
                    (int)addr->s6_addr[8], (int)addr->s6_addr[9],
                    (int)addr->s6_addr[10], (int)addr->s6_addr[11],
                    (int)addr->s6_addr[12], (int)addr->s6_addr[13],
                    (int)addr->s6_addr[14], (int)addr->s6_addr[15]);
                     printf("\nExpanded ipv6 Addr %s\n",str);
                }
    
                int main(int argc,char *argv[])
                {
                    struct in6_addrr ipv6;
                    printf("\nGiven IPv6 Addr %s\n",argv[1]);
                    if(inet_pton(AF_INET6,argv[1],&ipv6.addr))
                    {
                        ipv6_expander(&ipv6.addr);
                    }
                    else
                    {
                        printf("\n error\n");
                    }
                    return;
                }
    

提交回复
热议问题