一、地址格式转换
1、第一个函数
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
int inet_pton(int af , const char * src ,void * dst);
(1)功能:将点分十进制格式的地址字符串转换为网络字节序整型数
(2)返回值:成功返回1,错误返回-1
(3)参数:
----af :转换格式 AF_INET(IPV4)或者AF_INET6(IPV6)
---- src :点分格式的地址
----- dst:转换后的整型变量的地址
2、第二个函数
const char * inet_ntop(int af , const void * src , char * dst , socklen_t cnt);
(1)功能:将网络字节序整型数转换为点分格式的IP地址
(2)返回值:成功返回转换后的地址,错误返回NULL
(3)参数:
----af :转换格式 AF_INET(IPV4)或者AF_INET6(IPV6)
---- src :整型变量的地址
----- dst:用来存储转换后的数据的地址
------cnt:存储空间的大小
示例:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <netdb.h>
int main()
{
int addrnum;
char addrstring[16] = "127.0.0.1";
printf("address in dotted-quad format is %s\n",addrstring);
inet_pton(AF_INET,addrstring,&addrnum);
printf("address in network byteorder integer is 0x%x\n",addrnum);
char addrstring2[16] = "";
if(inet_ntop(AF_INET,&addrnum,addrstring2,16) == NULL)
{
perror("inet_ntop");
}
printf("address in dotted - quad format is %s \n",addrstring2);
return 0;
}
运行结果:
[root@rac2 ~]# ./addrformat
address in dotted-quad format is 127.0.0.1
address in network byteorder integer is 0x100007f
address in dotted - quad format is 127.0.0.1