今天就跟大家聊聊有关Python中怎么获取主机ip地址,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

import socket

import struct

import fcntl

import commands


def getLocalIP():

status,output=commands.getstatusoutput("hostname -i")

if status :

return '127.0.0.1'

else :

return output


def getip(ethname):

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

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


if __name__=='__main__':

print "getip :" , getip('eth0')

print "getLocalIP :", getLocalIP()

注意 本案例中 我写的是 eth0 , 如果是生产环境做了网卡绑定的话 需要使用 getip(bond0)
执行结果

[yangyidba@rac310:31:12 ~]

$ python getip.py

getip : 10.10.15.12

getLocalIP : 10.10.15.12


还有shell 的实现方式,可以使用 以下shell 方式 替代python 实现中的hostname -i:

host `hostname --fqdn` 2>/dev/null | awk '{print $NF}'

10.10.15.12


ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6|awk '{print $2}'|tr -d "addr:"

10.10.15.12


ifconfig|grep -v "127.0.0.1" | sed -n '/inet addr/s/^[^:]*:\([0-9.]\{7,15\}\) .*/\1/p'

10.10.15.12

看完上述内容,你们对Python中怎么获取主机ip地址有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。