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'))
posted @ 2018-12-17 14:52  陈富林  阅读(331)  评论(0编辑  收藏  举报