Reputation:
I want to find the network id using the bitwise operation between ipaddress and and subnetmask in python. I want to go with this traditional method my sample code is here
hostname=input("Enter the IP Address: ")
print(hostname)
if hostname >= "0.0.0.0" and hostname <= "127.255.255.255":
print("Class A")
print("The default subnet mask is: 255.0.0.0")
j=(hostname & 255.0.0.0)
print("The network id is ",j)
Upvotes: 0
Views: 1394
Reputation: 412
Since you are taking input, always ensure you sanitize the input.
use ipaddress.ip_interface() or ipaddress.ip_network()
to make sure the input given is a valid IP first.
Also your input hostname
is a string, so the bitwise operation will fail.
Once you use ipaddresss.ip_address(hostname)
, you'll get an IPv4Address
object which will allow you to check numerous properties.
There are other helper functions in ipaddress
standard package for taking CIDR values and creating IPvXNetwork
objects as well, maybe that's what you are looking for, check ipaddress HOW-TO
It would be roughly as follows:
import ipaddress
try:
inp = input("Enter the IP Address: ")
iface = ipaddress.ip_interface(inp)
except ValueError as e:
# crude way of handling and printing errors
# there are elegant ways to handle and proceed
print(e)
exit(1)
else:
netword_id = iface.network
hostname = iface.ip
NOTE: I made some edits to the original answer, you probably want to use ipaddress.ip_interface()
Upvotes: 1