python 获取本机ip地址的两个方法
更新时间:2013年02月25日 16:10:46 作者:
用python 获取本机ip地址的多种方法,需要的朋友可以参考下
第一种:
复制代码 代码如下:
import socket
import fcntl
import 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])
#get_ip_address('lo')环回地址
#get_ip_address('eth0')主机ip地址
第二种:
复制代码 代码如下:
def get_local_ip(ifname):
import socket, fcntl, struct
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
inet = fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15]))
ret = socket.inet_ntoa(inet[20:24])
return ret
print get_local_ip("eth0")
相关文章
Python3网络爬虫之使用User Agent和代理IP隐藏身份
这篇文章主要介绍了Python3网络爬虫之使用User Agent和代理IP隐藏身份,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2017-11-11
Python面向对象程序设计之私有变量,私有方法原理与用法分析
这篇文章主要介绍了Python面向对象程序设计之私有变量,私有方法,结合实例形式分析了Python面向对象程序设计中私有变量,私有方法相关概念、原理、用法及操作注意事项,需要的朋友可以参考下2020-03-03


最新评论