Python can be used to obtain the IP address of the local machine in a simple way. However, the methods in Windows and Linux are slightly different,
Method 1 for obtaining an IP address in Windows
When using dial-up Internet access, there is usually a local IP address and an Internet IP address. Using python, you can easily get the two IP addresses and use the gethostbyname and gethostbyname_ex functions to implement them.
Import socketlocalip = socket. gethostbyname (socket. gethostname () # obtain the local ipprint "local IP: % s" % localip iplist = socket. gethostbyname_ex (socket. gethostname () for I in iplist: If I! = Localip: Print "external IP: % s" % I
Method 2
import socket myname = socket.getfqdn(socket.gethostname())myaddr = socket.gethostbyname(myname)
How to obtain IP addresses in Linux
The above method can also be used in Linux. In addition, you can use the following method to obtain the local IP address in Linux.
Uses the Linux siocgifaddr IOCTL to find the IP address associated with a network interface, given the name of that interface, e.g. "eth0 ". the address is returned as a string containing a dotted quad.
import socketimport fcntlimport struct def get_ip_address(ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl( s.fileno(), 0x8915, # SIOCGIFADDR struct.pack('256s', ifname[:15]) )[20:24])
http://www.pythonclub.org/python-network-application/get-ip-address