0

I am writing a python script where I am monitoring the network status. I have Raspberry pi in which I am using Python 2.7. If the network is not available, script first checks if the network credentials are still saved in file wpa_supplicant.conf (/etc/wpa_supplicant/wpa_supplicant.conf). If it is not saved, then the script writes ssid and password in the file and run the below command to start the wlan0 to connect to wifi:

        ret = subprocess.call(['sudo /sbin/ifup --force wlan0'], shell=True)
        if ret is 0:
            print("Connection successfully")
        else:
            print("Unable to connect")

This connects the wifi to the given ssid.

Now the problem is the above commands return 0 if it runs successfully. But lets say if the wifi network is not available at that moment it will still show 0. How can we detect the network which we are trying to connect is not available.

Thanks.

S Andrew
  • 5,592
  • 27
  • 115
  • 237
  • this can help https://stackoverflow.com/questions/31868486/list-all-wireless-networks-python-for-pc – Kallz Aug 26 '17 at 10:57

1 Answers1

0

Interfaces has something called Administrative and Operational state.

  • Administrative state (in code its called admin state) means if the link is UP/DOWN this can happens when the physical link change state or admin shut/no shut using CLI (Command Link Interface).

  • Operational state (in code its called operstate) relates to protocol UP/DOWN state, this happens when ARP is resolved and interface gets IP address. If Admin state is DOWN, operational state will also be down. This can be checked using command cat /sys/class/net/wlp2s0/operstate where wlp2s0 is my wifi interface.

For your need you can use /sys/class/net/wlp2s0/operstate to find out state of the interface. For more details check this link.

Following is the snippet of output on my machine:

mdeore@mdeore-Lenovo:~$ awk '{ split(FILENAME, array, "/"); print array[5] ": " $1 }' $(find /sys/class/net/*/operstate ! -type d)
enp1s0: down
lo: unknown
wlp2s0: up
Milind Deore
  • 2,887
  • 5
  • 25
  • 40