2014年7月28日 星期一

Python get Network IP

一些取得ip的方法:

>>> import socket
>>> def getNetworkIp():
...     s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
...     s.connect(('www.google.com', 0))
...     return s.getsockname()[0]
...
>>> getNetworkIp()
'192.168.101.253'
>>>
-------------------------------------------------------------------------------------
>>> import socket, struct, fcntl
>>> sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> sockfd = sock.fileno()
>>> SIOCGIFADDR = 0x8915
>>> def get_ip(iface = 'eth0'):
...    ifreq = struct.pack('16sH14s', iface, socket.AF_INET, '\x00'*14)
...    try:
...       res = fcntl.ioctl(sockfd, SIOCGIFADDR, ifreq)
...    except:
...       return None
...    ip = struct.unpack('16sH2x4s8x', res)[2]
...    return socket.inet_ntoa(ip)
...
>>> get_ip('eth0')
'192.168.101.253'
>>>
iF  Python3 with one modification: struct.pack('16sH14s', iface, socket.AF_INET, '\x00'*14) should be replaced with struct.pack('16sH14s', iface.encode('utf-8'), socket.AF_INET, b'\x00'*14)
-------------------------------------------------------------------------------------
>>> import commands
>>> commands.getoutput("/sbin/ifconfig").split("\n")[1].split()[1][5:]
'192.168.101.253'
-------------------------------------------------------------------------------------
#!/usr/bin/python
# module for getting the lan ip address of the computer

import os
import socket

if os.name != "nt":
    import fcntl
    import struct
    def get_interface_ip(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])

def get_lan_ip():
    ip = socket.gethostbyname(socket.gethostname())
    if ip.startswith("127.") and os.name != "nt":
        interfaces = ["eth0","eth1","eth2","wlan0","wlan1","wifi0","ath0","ath1","ppp0"]
        for ifname in interfaces:
            try:
                ip = get_interface_ip(ifname)
                break;
            except IOError:
                pass
    return ip
print get_lan_ip()
----------------------------------------------------------------------------------
>>> import commands
>>> ips = commands.getoutput("/sbin/ifconfig | grep -i \"inet\" | grep -iv \"inet6\" | " +"awk {'print $2'} | sed -ne 's/addr\:/ /p'")
>>> print ips
 192.168.101.253
 127.0.0.1
>>>
---------------------------------------------------------------------------------
>>> import socket, subprocess, re
>>> def get_ipv4_address():
...     """
...     Returns IP address(es) of current machine.
...     :return:
...     """
...     p = subprocess.Popen(["ifconfig"], stdout=subprocess.PIPE)
...     ifc_resp = p.communicate()
...     patt = re.compile(r'inet\s*\w*\S*:\s*(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})')
...     resp = patt.findall(ifc_resp[0])
...     print resp
...
>>> get_ipv4_address()
['192.168.101.253', '127.0.0.1']
>>>

沒有留言: