Linux C判斷兩個IPv6地址是否相等的方法
阿新 • • 發佈:2019-01-02
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