新聞中心
今天就跟大家聊聊有關(guān)Python中怎么獲取主機(jī)ip地址,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
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()
注意 本案例中 我寫(xiě)的是 eth0 , 如果是生產(chǎn)環(huán)境做了網(wǎng)卡綁定的話(huà) 需要使用 getip(bond0)
執(zhí)行結(jié)果
[yangyidba@rac3 10:31:12 ~]
$ python getip.py
getip : 10.10.15.12
getLocalIP : 10.10.15.12
還有shell 的實(shí)現(xiàn)方式, 可以使用 以下shell 方式 替代python 實(shí)現(xiàn)中的 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
看完上述內(nèi)容,你們對(duì)Python中怎么獲取主機(jī)ip地址有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注創(chuàng)新互聯(lián)-成都網(wǎng)站建設(shè)公司行業(yè)資訊頻道,感謝大家的支持。
本文標(biāo)題:Python中怎么獲取主機(jī)ip地址-創(chuàng)新互聯(lián)
網(wǎng)頁(yè)網(wǎng)址:http://www.ef60e0e.cn/article/dhphss.html