osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Unable to get the gateway IP of wlan interface using python code


Hi Wildman,

The below snippet seems to be fine, how can I specify to get the specific
wlan0 interface gateway IP in the below code snippet?

#########################
#!/usr/bin/env python

import socket
import struct

def get_gateway_ip():
    try:
        with open("/proc/net/route", "r") as f:
            route = f.readlines()
    except IOError:
        return None
    for line in route:
        fields = line.strip().split()
        if fields[1] != "00000000" or not int(fields[3], 16) & 2:
            continue
        gateway = socket.inet_ntoa(struct.pack("<L", int(fields[2], 16)))
        break
    return gateway

print get_gateway_ip()
#########################


Many Thanks in advance,
Srini


On Tue, Nov 13, 2018 at 5:16 AM Wildman via Python-list <
python-list at python.org> wrote:

> I tried posting this already but it didn't make it.  I am
> trying again...
>
> On Tue, 13 Nov 2018 01:07:06 +0530, srinivasan wrote:
>
> > Dear Python Experts,
> >
> > *First method:*
> >
> > I need to get the IP address basically the gateway IP
>
> I am assuming your platform is Linux.  If I am incorrect then
> ignore this post.
>
> The code below reads /proc/net/route to obtain the gateway and
> then prints it.  It can be run as-is from a terminal.
>
> #########################
> #!/usr/bin/env python
>
> import socket
> import struct
>
> def get_gateway_ip():
>     try:
>         with open("/proc/net/route", "r") as f:
>             route = f.readlines()
>     except IOError:
>         return None
>     for line in route:
>         fields = line.strip().split()
>         if fields[1] != "00000000" or not int(fields[3], 16) & 2:
>             continue
>         gateway = socket.inet_ntoa(struct.pack("<L", int(fields[2], 16)))
>         break
>     return gateway
>
> print get_gateway_ip()
> #########################
>
> --
> <Wildman> GNU/Linux user #557453
> The cow died so I don't need your bull!
> --
> https://mail.python.org/mailman/listinfo/python-list
>