您的位置:首页 > 理论基础 > 计算机网络

通过Python在windows和linux中获取当前网络IP地址的一些方法

2016-11-20 13:38 916 查看
获取当前网络的IP地址主流的方式有三种,我实验时,环境是ubuntu16.04,基于Python2.7,发现前两种都是获取的‘127.0.0.1’,这不是我想要的,而第三种这可以很好的解决我的问题,下面列出这三种方法:

方法一:通过socket.gethostbyname方法获得

import socket

localIP = socket.gethostbyname(socket.gethostname())#得到本地ip

print "local ip:%s "%localIP

方法二:通过socket.gethostbyname_ex方法获得本机主机名和ip地址列表

import socket

ipList = socket.gethostbyname_ex(socket.gethostname())

print(ipList)

方法三:通过指定网卡接口的名字

import socket, fcntl, struct

def get_ip(ifname):

        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

         return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15]))[20:24])

这里的网卡接口名字可以在“连接信息”-->“接口:”--->“以太网(***)”  括号里面的就是网卡接口名

参考链接:
http://blog.csdn.net/tao_627/article/details/49967185 http://blog.csdn.net/tao_627/article/details/49967185 http://www.jb51.net/article/62559.htm
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息