Last active
April 9, 2022 17:40
-
-
Save wuriyanto48/32728f495942086dc87c06cbae57405b to your computer and use it in GitHub Desktop.
Get Network value from IP with Python
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
def encode_uint32(n: int): | |
res = [] | |
for i in range(4): | |
r_shift = 24 - 8 * i | |
d = (n >> r_shift) & 0xFF | |
res.append(d) | |
return res | |
def decode_uint32(l: list, order='be'): | |
if order == 'le': | |
l.reverse() | |
dec = 0 | |
for i in range(len(l)): | |
l_shift = 24 - i * 8 | |
dec |= (l[i] & 0xFF) << l_shift | |
return dec | |
# params: | |
# ip = eg: '192.0.2.12' | |
# netmask = eg: '255.255.255.0' | |
def get_subnet_info(ip: str, netmask: str): | |
ip_ints = [int(i, base=10) for i in ip.split('.')] | |
netmask_ints = [int(i, base=10) for i in netmask.split('.')] | |
ip_int32_format = decode_uint32(ip_ints) | |
netmask_int_32_format = decode_uint32(netmask_ints) | |
network = netmask_int_32_format & ip_int32_format | |
full_mask_int_32_format = decode_uint32([255, 255, 255, 255]) | |
host_remider_bit = full_mask_int_32_format-netmask_int_32_format | |
network_ints = encode_uint32(network) | |
network_str = '.'.join([str(n) for n in network_ints]) | |
print('your IP Address : ', ip) | |
print('your Netmask : ', netmask) | |
print('network : ', network_str) | |
print('number of host in this network : ', host_remider_bit) | |
ip = '192.0.2.11' | |
netmask = '255.255.255.0' | |
# usually written with format 192.0.2.11/24 | |
# where 192.0.2.11 = IP address | |
# and 24 = number of network bits in decimal | |
# 24 = 11111111.11111111.11111111.00000000 | |
# = 255.255.255.0 | |
get_subnet_info(ip, netmask) | |
# Rose Emoji with different encoding | |
[print(b) for b in '🌹'.encode(encoding='utf-8')] | |
s_utf8 = bytes([240, 159, 140, 185]).decode(encoding='utf-8') | |
print(s_utf8) | |
print('----------------------------------') | |
[print(b) for b in '🌹'.encode(encoding='utf-16')] | |
s_utf16 = bytes([60, 216, 57, 223]).decode(encoding='utf-16') | |
print(s_utf16) | |
print('----------------------------------') | |
[print(b) for b in '🌹'.encode(encoding='utf-32')] | |
s_utf32 = bytes([57, 243, 1, 0]).decode(encoding='utf-32') | |
print(s_utf32) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment