概述
IP格式最常见的是使用点分10进制表示,如: xx.xx.xx.xx (IPV4地址)。
IP地址分为两类:IPv4地址和IPv6地址。
- IPv4 地址用32位来表示;
- IPv6 地址用128位来表示;
由于二进制数太长,人们为了便于记忆和识别,就把每一段8位编为一组,每组之间用点号分开。然后将每个字节(八位组)转换为等值的十进制数,大小为0至255。
IP 地址分为A、B、C、D、E等 5 大类,由IP地址第一字节的几个最高位来定义和区分,简要如下表所示
inet_pton
函数原型
#include <arpa/inet.h>
int inet_pton(int af, const char *src, void *dst);
This function converts the character string src into a network address structure in the af address family, then copies the network address structure to dst. The af argument must be either AF_INET or AF_INET6.
返回值
inet_pton() returns 1 on success (network address was successfully converted). 0 is returned if src does not contain a character string representing a valid network address in the specified address family. If af does not contain a valid address family, -1 is returned and errno is set to EAFNOSUPPORT.
inet_ntop
函数原型
#include <arpa/inet.h>
const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
This function converts the network address structure src in the af address family into a character string. The resulting string is copied to the buffer pointed to by dst, which must be a non-NULL pointer. The caller specifies the number of bytes available in this buffer in the argument size.
返回值
On success, inet_ntop() returns a non-NULL pointer to dst. NULL is returned if there was an error, with errno set to indicate the error.
实例
#include <arpa/inet.h>
#include <stdio.h>
void TestIpv6()
{
char ipv6_addr[64];
//内嵌 IPv4 地址的 IPv6 地址
inet_pton(AF_INET6, "0:0:0:0:0:0:192.168.200.65", ipv6_addr);
char ipv6_str[64]={'\0'};
inet_ntop(AF_INET6, ipv6_addr, ipv6_str, 64);
printf("%s\n", ipv6_str);
}
void TestIpv4()
{
int ipv4_addr;
inet_pton(AF_INET, "192.168.200.65", &ipv4_addr);
printf("%d\n", ipv4_addr);
char ipv4_str[64]={'\0'};
inet_ntop(AF_INET, &ipv4_addr, ipv4_str, 64);
printf("%s\n", ipv4_str);
}
int main()
{
TestIpv6();
TestIpv4();
return 0;
}
上面代码输出结果为:
::192.168.200.65
1103669440
192.168.200.65
如果将地址设置为全 0,
inet_pton(AF_INET6, "0:0:0:0:0:0:0.0.0.0", ipv6_addr);
则打印结果为:
::