1 2 3 4 5 6 7 8 9 10
| import socket
def print_machine_info(): host_name = socket.gethostname() ip_address = socket.gethostbyname(host_name) print "Host name: %s"%host_name print "IP address: %s"%ip_address
if __name__ == "__main__": print_machine_info()
|
Running this script,we will get the basic info about our machine
1 2 3 4 5 6 7 8 9 10 11
| import socket
def get_remote_machine_info(): remote_host = 'www.fuckbaidu.com' try: print "IP address: %s"%socket.gethostbyname(remote_host) except socket.error,err_msg: print "%s: %s"%(remote_host, err_msg)
if __name__ == "__main__": get_remote_machine_info()
|
The Python socket library has utilities to deal with the various
IP address format.Here,we will use two of them:inet_aton() and
inet_ntoa()
1 2 3 4 5 6 7 8 9 10 11
| import socket from binascii import hexlify
def convert_ip4_address(): for ip_addr in ['127.0.0.1','192.168.1.1']: packed_ip_addr = socket.inet_aton(ip_addr) unpacked_ip_addr = socket.inet.ntoa(ip_addr) print "IP address: %s => Packed:%s, Unpacked:%s"%(ip_addr,hexlify(packed_ip_addr), unpacked_ip_addr)
if __name__ == "__main__": convert_ip4_address()
|