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. The following describes in detail how to obtain the IP address in Windows... 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. The following describes in detail:
How to obtain an IP address in Windows
Method 1 socket module
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.
# Use the socket module import socket # obtain the local iplocalIP = socket. gethostbyname (socket. gethostname () print "local ip: % s" % localIP ipList = socket. gethostbyname_ex (socket. gethostname () for I in ipList: if I! = LocalIP: print "external IP: % s" % I
Or
# Introduce the socket module import socketmyname = socket. getfqdn (socket. gethostname () myaddr = socket. gethostbyname (myname)
Method 2 use the regular expression and urllib2 module
This method obtains the public IP address by using the IP detection function provided by other websites, and then crawls the page using python for regular matching or obtaining. However, this method is more accurate.
Import re, urllib2from subprocess import Popen, PIPE print "The private IP address of the local machine is:" + re. search ('\ d + \. \ d + \. \ d + \. \ d + ', Popen ('ipconfig', stdout = PIPE ). stdout. read ()). group (0) # use interfaces provided by other websites to use urllib2 to obtain ipprint. "The local public IP address is:" + re. search ('\ d + \. \ d + \. \ d + \. \ d + ', urllib2.urlopen ("http://www.ip138.com "). read ()). group (0)
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.
import socketimport fcntlimport struct def get_ip_address(ifname): skt = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) print skt pktString = fcntl.ioctl(skt.fileno(), 0x8915, struct.pack('256s', ifname[:15])) print pktString ipString = socket.inet_ntoa(pktString[20:24]) print ipString return ipString print get_ip_address('lo')print get_ip_address('eth1')