Home >Backend Development >Python Tutorial >Use Python to obtain IP address under linux and windows
Using Python, you can get the local IP address in a very simple way. However, the methods under Windows and Linux are slightly different. Here is a detailed introduction:
How to obtain the IP address under Windows
Method 1: Use the socket module
If you use dial-up Internet access, you usually have a local IP and an external IP. You can easily get these two IPs using python. You can use the gethostbyname and gethostbyname_ex functions to achieve
#使用socket模块 import socket #得到本地ip localIP = 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
#引入socket模块 import socket myname = socket.getfqdn(socket.gethostname()) myaddr = socket.gethostbyname(myname)
Method 2 uses regular expressions and the urllib2 module
This method to obtain the public IP uses the IP detection function provided by other websites, and then uses python to crawl the page, and the regular match is obtained. But this method is more accurate
import re,urllib2 from subprocess import Popen, PIPE print "本机的私网IP地址为:" + re.search('\d+\.\d+\.\d+\.\d+',Popen('ipconfig', stdout=PIPE).stdout.read()).group(0) #利用其他网站提供的接口,使用urllib2获取其中的ip print "本机的公网IP地址为:" +re.search('\d+\.\d+\.\d+\.\d+',urllib2.urlopen("http://www.ip138.com").read()).group(0)
How to obtain the IP address under Linux
The above method can also be used under Linux. In addition, under Linux, you can also use the following method to obtain the machine IP address.
import socket import fcntl import 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')