python3 linux 下获取本地网卡ip

  • system ubuntu14.04
  • python3.6.1
def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
        s.fileno(),
        0x8915,  # SIOCGIFADDR
        struct.pack('256s', bytes(ifname[:15], 'utf-8'))
    )[20:24])

a = get_ip_address('eth0') # 网卡
print(a)

你可能感兴趣的:(Python,linux-ubun)