Last active
September 5, 2023 00:26
-
-
Save lihnux/fa507a90395f5890827a7351502c6978 to your computer and use it in GitHub Desktop.
一些网络相关的代码
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 判断一个IP地址,是否属于以下网段: | |
// 10.0.0.0/8, 169.254.0.0/16, 172.16.0.0/12, 192.168.0.0/16, 224.0.0.0/4, 255.255.255.255/32, fc00::/7, fe80::/10, ff00::/8 | |
#include <stdint.h> | |
#include <arpa/inet.h> | |
int is_special_ip(uint32_t ipv4) { | |
uint8_t first_octet = ipv4 >> 24; | |
if (first_octet == 10) return 1; | |
if (first_octet == 169 && (ipv4 & 0xFFFF0000) == 0xA9FE0000) return 1; | |
if (first_octet == 172 && (ipv4 & 0xFFF00000) == 0xAC100000) return 1; | |
if (first_octet == 192 && (ipv4 & 0xFFFF0000) == 0xC0A80000) return 1; | |
if (first_octet >= 224 && first_octet <= 239) return 1; | |
if (ipv4 == 0xFFFFFFFF) return 1; | |
return 0; | |
} | |
int is_special_ip6(struct in6_addr *addr) { | |
uint16_t *words = (uint16_t*)addr; | |
if (words[0] == 0xFC00) return 1; | |
if (words[0] == 0xFE80) return 1; | |
if (words[0] == 0xFF00) return 1; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment