Last active
October 23, 2024 07:19
-
-
Save smiley-yoyo/9c45173948c61df2b7b1ed0db0f895d6 to your computer and use it in GitHub Desktop.
python calc ip addr in network
This file contains hidden or 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
| import socket, struct | |
| from ipaddress import ip_address, ip_network | |
| # 错误代码,由于网络字节序为大字节序,而此代码试图使用小字节序处理掩码,因此当掩码不是刚好8的倍数时就会判断错误 | |
| def addr_in_network_wrong(ip, net_n_bits): | |
| ipaddr = struct.unpack('<L', socket.inet_aton(ip))[0] | |
| net, bits = net_n_bits.split('/') | |
| netaddr = struct.unpack('<L', socket.inet_aton(net))[0] | |
| netmask = ((1L << int(bits)) - 1) | |
| return ipaddr & netmask == netaddr & netmask | |
| # 正确代码 | |
| def addr_in_network(ip, net_n_bits): | |
| ipaddr = struct.unpack('!L', socket.inet_aton(ip))[0] | |
| net, bits = net_n_bits.split('/') | |
| netaddr = struct.unpack('!L', socket.inet_aton(net))[0] | |
| netmask = (0xFFFFFFFF >> int(bits)) ^ 0xFFFFFFFF | |
| return ipaddr & netmask == netaddr & netmask | |
| # 使用python3自带ipaddress库 | |
| def addr_in_network3(addr: str, net str) -> bool: | |
| return ip_address(addr) in ip_network(net) | |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
原先的代码有问题,只能判断/8 /16 /24 /32的子网,如果是/26这种就判断错误了,因为用的字节序是小字节序。已补充正确代码。