/*linux 下IP地址转换*/
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
/*1.整形转换成字符串格式*/
void ipv4_int_to_str(char *ipv4, unsigned int a)
{
struct in_addr addr;
addr.s_addr = a;
char *ip = inet_ntoa(addr);
strcpy(ipv4, ip);
}
void ipv6_int_to_str(char *IPdotdec, unsigned int ipv6_addr[])
{
struct in6_addr s;
int i;
int ipv6[4];
for(i = 0; i < 4; i++) {
ipv6[i] = htonl(ipv6_addr[i]);
}
memcpy(s.s6_addr,ipv6,4*sizeof(int));
inet_ntop(AF_INET6, (void *)&s, IPdotdec, INET6_ADDRSTRLEN);
}
/* 2.字符串转换成整形格式*/
void ipv4_str_to_int(char *ipv4, struct in_addr *s)
{
/*也可以使用inet_addr函数*/
inet_pton(AF_INET, ipv4, (void*)s);
}
void ipv6_str_to_int(char *ipaddr, unsigned int *ipv6)
{
struct in6_addr dst;
inet_pton(AF_INET6, ipaddr, (void *)&dst);
memcpy(ipv6, dst.s6_addr, sizeof(dst.s6_addr));
}
/*子网掩码地址, 转换为一个CIDR值*/
int mask_to_cidr(u_int32_t mask)
{
int i, n = 0,bits;
bits = sizeof(u_int32_t) * 8;
for(i = bits - 1; i >= 0; i--) {
if (mask & (0x01 << i)) {
n++;
}
}
return n;
}
int main(int argc, char **argv)
{
/*整形转换为字符型*/
char ipv4_s[30];
ipv4_int_to_str(ipv4_s, 84215041);
printf("ipv4 string addr:%s\n", ipv4_s);
char ipv6_s[50];
unsigned int ipv6_i[4];//以一个无符号整形数组存放ipv6地址
ipv6_i[0] = 0x20140000;
ipv6_i[1] = 0x0;
ipv6_i[2] = 0x0;
ipv6_i[3] = 0x1;
ipv6_int_to_str(ipv6_s, ipv6_i);
printf("ipv4 string addr:%s\n", ipv6_s);
/*字符类型转换成整形*/
strcpy(ipv4_s,"192.168.20.100");
struct in_addr s;
ipv4_str_to_int(ipv4_s,&s);
printf("ipv4 integar addr:%x\n",s.s_addr);
strcpy(ipv6_s,"2014::1");
unsigned int ipv6[4];
ipv6_str_to_int(ipv6_s, ipv6);
int i;
printf("ipv6 integar addr:");
for(i=0;i<4;i++) {
printf("%x ",htonl(ipv6[i]));
}
printf("\n");
return 0;
}