Python 獲取本機ip地址

通過socket.gethostbyname(socket.gethostname())的方式只能獲取到自環網地址127.0.0.1,要獲取到其他網卡(如eth0)ip地址,需通過ioctl實現:

import socket
import fcntl
import struct

def getip(ifname):
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        netaddr = fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15].encode('utf-8')))
        ipaddr = socket.inet_ntoa(netaddr[20:24])
    
        return ipaddr
    except OSError as oe:
        print ('No such device: ', ifname)

print ('lo: ', getip('lo'))
print ('eth0: ', getip('eth0'))
print ('eth1: ', getip('eth1'))



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章