Linux下 Python:利用socket.inet_ntoa获取机器网卡IP地址

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#************************************************************************#
#Shell Name:
#functions:
#parameter:
#content:
#************************************************************************#

import socket
import fcntl
import struct

localip=''

def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    ipaddr = socket.inet_ntoa(fcntl.ioctl(
        s.fileno(),
        0x8915,  # SIOCGIFADDR
        struct.pack('256s', ifname[:15])
    )[20:24])
    s.close()
    return ipaddr


if localip.strip()=='':
  try:
    localip = get_ip_address('eth0')
  except IOError:
    localip = get_ip_address('br0')
 
print 'localip',localip

猜你喜欢

转载自blog.csdn.net/qq_42609381/article/details/81118508