Use Python to obtain IP address under linux and windows

高洛峰
Release: 2016-10-18 14:47:04
Original
1722 people have browsed it

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
Copy after login

or

#引入socket模块
import socket
myname = socket.getfqdn(socket.gethostname())
myaddr = socket.gethostbyname(myname)
Copy after login

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)
Copy after login

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')
Copy after login


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!