用PYTHON获取本机的IP地址

来源:互联网 发布:英语语音识别软件 编辑:程序博客网 时间:2024/05/23 21:42
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,  # SIOCGIFADDR
        struct.pack('256s', ifname[:15])
    )[20:24])


#get_ip_address('lo')环回地址
#get_ip_address('eth0')主机ip地址