Python 获取IP地址的简单示例

Python 获取IP地址的简单示例,第1张

概述Python 获取IP地址的简单示例 对python这个高级语言感兴趣的小伙伴,下面一起跟随内存溢出 jb51.cc的小编两巴掌来看看吧!

使用Python可以用很简单的方法得到本机IP地址,不过在windows和linux下的方法稍有不一样的,下面就来详细介绍下:

windows下获得IP地址的方法

 

方法一 使用socket模块

使用拨号上网的话,一般都有一个本地ip和一个外网IP,使用python可以很容易的得到这两个ip 使用gethostbyname和gethostbyname_ex两个函数可以实现

# @param linux及windows下使用Python获取IP地址# @author 内存溢出 jb51.cc|www.jb51.cc #使用socket模块import socket#得到本地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# End www.jb51.cc

或者

# @param linux及windows下使用Python获取IP地址# @author 内存溢出 jb51.cc|www.jb51.cc #引入socket模块import socketmyname = socket.getfqdn(socket.gethostname())myaddr = socket.gethostbyname(myname)# End www.jb51.cc

方法二 使用正则表达式和urllib2模块

该方法获取公网IP使用的是利用其他网站提供的IP检测功能,然后在使用python抓取页面,正则匹配或得。不过该方法比较准确哦

# @param linux及windows下使用Python获取IP地址# @author 内存溢出 jb51.cc|www.jb51.cc import re,urllib2from subprocess import Popen,PIPE       print "本机的私网IP地址为:" + re.search('\d+\.\d+\.\d+\.\d+',Popen('ipconfig',stdout=PIPE).stdout.read()).group(0)       #利用其他网站提供的接口,使用urllib2获取其中的ipprint "本机的公网IP地址为:" + re.search('\d+\.\d+\.\d+\.\d+',urllib2.urlopen("http://www.ip138.com").read()).group(0)# End www.jb51.cc
linux下获得IP地址的方法

上面的方法在linux下也可以使用,除此之外,linux下还可以用下面的方法得到本机IP地址。
 

# @param linux及windows下使用Python获取IP地址# @author 内存溢出 jb51.cc|www.jb51.cc 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')# End www.jb51.cc
总结

以上是内存溢出为你收集整理的Python 获取IP地址的简单示例全部内容,希望文章能够帮你解决Python 获取IP地址的简单示例所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/1199907.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-04
下一篇2022-06-04

发表评论

登录后才能评论

评论列表(0条)

    保存