Availability of IP Address - Python
How to check the availability of an IP address in python?
For example, I wan't to change my system's IP address to 192.168.112.226 statically overriding the dhcp provided address. The default gateway is 192.168.112.1. But I wan't to check before if anyone is usi开发者_开发问答ng 192.168.112.226 before assigning to myself.
Usually do this in command line from bash. I check with ping 192.168.112.226. If host is unreachable, I use 'ifconfig' and 'route' to assign it to myself.
How to automate this using python?
PS: I prefer python so that I can use python-notify to beautify the output whether success or failure.
This is so bad in so many ways I can't even explain how awfull this is.
Why do you want this? Could you please tell us that, and we could come up with a much better answer than this utterly uggly "sollution"?
If you have a Linux/Unix system, you can make your DHCP client to request the DHCP-server to give you a specific IP address if the DHCP server know it's free. How to do this depends on the distribution.
There are two problems I see that you will create with your "sollution".
As some other has written, you could check to see that the IP is "free" right now, but the machine that own that IP address might start right after your test. Using its IP address, wich you have kidnapped.
If the DHCP server don't know that you have kidnapped an IP address, it could give it out to someone else.
Whatever it will break the network for that computer and yours, generating lots of work, and possible anger for/to the network administrator. And you don't want that, do you?
Okay, if you want to use bash, you can import os module or subprocess module.
for example:
import os
command = os.system('pint 192.168.112.226')
if command == 0: #Sucess
#write os.system() and give it ifconfig and route commands as parameter.
else: print "This IP is used by another person in your network."
you can read more about os.system and subprocess in python, by importing them and writing help(subprocess)
for example.
You can use socket.gethostbyaddr() to find if IP Address is being in use or not.
import sys, os, socket
# Stores the IP Address
ip_address = sys.argv[1]
try:
socket.gethostbyaddr(ip_address)
# If previous line doesn't throw exception, IP address is being used by someone
print "No"
except socket.herror:
# socket.gethostbyaddr() throws error, so IP is not being used at present
# You can write os.system() and give it ifconfig and route commands as parameter.
print "Yes"
The problem with this code is that method.gethostbyaddr() takes lot of time to throw socket.herror if IP address is not in use on the network.
If you name this script as isIPAvailable.py, then it can be called by:
python isIPAvailable.py 192.168.112.226
精彩评论