python获取网卡的IP地址

用这个函数可以实现功能:

import socket
import fcntl
import struct

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

使用 get_ip_address('eth0') 就可以获得eth0网卡的IP地址

猜你喜欢

转载自songpengfei.iteye.com/blog/1697359