红联Linux门户
Linux帮助

Linux C判断两个IPv6地址是否相等的方法

发布时间:2016-02-23 16:22:39来源:linux网站作者:szkbsgy

IPv6地址用冒号和16进制数表示,其中遇到连续的0可以作省略处理,如2001:0:0:0:0:0:0:1可以写成2001::1,这样对于书写很方便,但是带来一个额外的问题:两个地址比较的时候不能像IPv4那样调用字符串比较函数进行比较。本文通过比较两个IPv6地址的网络字节序来判断是否相等。


#include <stdio.h> 
#include <arpa/inet.h> 

int ipv6_equal(char *addr1, char *addr2) 

int ret = -1; 
int i = 0; 
unsigned char n_addr1[16] = {-1}; 
unsigned char n_addr2[16] = {-1}; 

if (!addr1) { 
printf("addr1 is NULL\n"); 
return -1; 

if (!addr2) { 
printf("addr2 is NULL\n"); 
return -1; 

ret = inet_pton(AF_INET6, addr1, &(n_addr1)); 
if (ret <= 0 ) { 
if (ret == 0) { 
printf("addr1: Invalid IPv6 address\n"); 

return -1; 

ret = inet_pton(AF_INET6, addr2, &(n_addr2)); 
if (ret <=0 ) { 
if (ret == 0) { 
printf("addr2: Invalid IPv6 address\n"); 

return -1; 

for (i = 0; i < 16; i++) { 
//printf("i: %d, addr1: %u, addr2: %u\n", i, n_addr1[i], n_addr2[i]); 
if (n_addr1[i] != n_addr2[i]) { 
return 1; 
}

return 0; 

int main(void) 

if (ipv6_equal("2001::1", "2001::1") == 0) { 
printf("test: 2001::1 equal 2001::1\n"); 

if (ipv6_equal("2001:0:0:0:0:0:0:1", "2001::1") == 0) { 
printf("test: 2001:0:0:0:0:0:0:1 equal 2001::1\n"); 

if (ipv6_equal("2001::1", "2001::4") == 1) { 
printf("test: 2001::1 not equal 2001::4\n"); 

if (ipv6_equal("2001:::1", "2001::4") == -1) { 
printf("test: Invalid address\n"); 
}
return 0; 


结果:

test: 2001::1 equal 2001::1
test: 2001:0:0:0:0:0:0:1 equal 2001::1
test: 2001::1 not equal 2001::4
addr1: Invalid IPv6 address
test: Invalid address


本文永久更新地址:http://www.linuxdiyf.com/linux/18340.html