Get the IP address of WIFI interface

Neal Becker ndbecker2 at gmail.com
Sun May 15 07:04:27 EDT 2011


Far.Runner wrote:

> Hi python experts:
> There are two network interfaces on my laptop: one is 100M Ethernet
> interface, the other is wifi interface, both are connected and has an ip
> address.
> The question is: How to get the ip address of the wifi interface in a python
> script without parsing the output of a shell command like "ipconfig" or
> "ifconfig"?
> 
> OS: Windows or Linux
> 
> F.R

Here's some useful snippits for linux:

def get_default_if():
    f = open('/proc/net/route')
    for i in csv.DictReader(f, delimiter="\t"):
        if long(i['Destination'], 16) == 0:
            return i['Iface']
    return None

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])





More information about the Python-list mailing list