python 获取本机的IP

  • 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".encode(), ifname[:15].encode())  
        )[20:24])

    print ("LoopBack Addr: " + get_ip_address('lo'))
    print ("My IP Address: " + get_ip_address('eth0'))
原文地址:https://www.cnblogs.com/chenfulin5/p/10131515.html