python获取ip地址的代码

发布时间:2019-08-18编辑:脚本学堂
python获取ip地址的代码

python获取IP地址的代码,有需要的朋友可以参考下。

文件名:getip.py
 

复制代码 代码如下:

    #!/usr/bin/python
    #conding:utf-8
     
    import socket,fcntl,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])
        
    print get_ip_address('lo')
    print get_ip_address('wlan0')

执行结果:
    $ python getip.py
    127.0.0.1
    192.168.2.102

本机信息:
    $ ifconfig

    lo Link encap:Local Loopback
    inet addr:127.0.0.1 Mask:255.0.0.0
    inet6 addr: ::1/128 Scope:Host
    UP LOOPBACK RUNNING MTU:16436 Metric:1
    RX packets:35657 errors:0 dropped:0 overruns:0 frame:0
    TX packets:35657 errors:0 dropped:0 overruns:0 carrier:0
    collisions:0 txqueuelen:0
    RX bytes:3487215 (3.4 MB) TX bytes:3487215 (3.4 MB)

    wlan0 Link encap:Ethernet HWaddr 20:7c:8f:69:f2:b5
    inet addr:192.168.2.102 Bcast:192.168.2.255 Mask:255.255.255.0
    inet6 addr: fe80::227c:8fff:fe69:f2b5/64 Scope:Link
    UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
    RX packets:14399 errors:0 dropped:0 overruns:0 frame:0
    TX packets:17826 errors:0 dropped:0 overruns:0 carrier:0
    collisions:0 txqueuelen:1000
    RX bytes:6866206 (6.8 MB) TX bytes:2687637 (2.6 MB)