Waiting for Network Interface to be ready

Waiting for Network Interface to be ready

Postby marcoVDM » Thu Aug 18, 2016 12:50 pm

I have a program that auto starts on a headless Raspberry Pi and so far I have built in a 10 second wait before it actually starts running. Sometimes my WiFi takes a bit longer than expected to establish a connection with my AP.
Even the 10 second waiting time also appears to occasionally not be long enough, for what ever reason. IMO it's bad programming so:

What is the correct procedure to wait for a network interface to be ready before attempting to bind to a socket?

Thanks in advance
Posts: 6
Joined: Sun Aug 14, 2016 4:15 pm

Re: Waiting for Network Interface to be ready

Postby Ofnuts » Thu Aug 18, 2016 3:31 pm

I would do it the other way: try to bind, and in case of failure sleep a bit (.2s-2s) and retry...
This forum has been moved to http://python-forum.io/. See you there.
User avatar
Posts: 2659
Joined: Thu May 14, 2015 9:46 am
Location: Paris, France, EU, Earth, Solar system, Milky Way, Local Cluster, Universe #32987440940987

Re: Waiting for Network Interface to be ready

Postby wavic » Thu Aug 18, 2016 5:29 pm

Check if you wifi is up:
Code: Select all
import netifaces

if 'wlan0' in netifaces.interfaces():
    # run the program code

Here are some examples.

Or get USSID or None if not conected in that way. The code is not writen by me.

Code: Select all
import array
import fcntl
import socket
import struct

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
maxLength = {
    "interface": 16,
    "essid": 32
calls = {

def getESSID(interface):
    """Return the ESSID for an interface, or None if we aren't connected."""
    essid = array.array("c", "\0" * maxLength["essid"])
    essidPointer, essidLength = essid.buffer_info()
    request = array.array("c",
        interface.ljust(maxLength["interface"], "\0") +
        struct.pack("PHH", essidPointer, essidLength, 0)
    fcntl.ioctl(sock.fileno(), calls["SIOCGIWESSID"], request)
    name = essid.tostring().rstrip("\0")
    if name:
      return name
    return None
Posts: 165
Joined: Wed May 25, 2016 8:51 pm

Return to Networking

Who is online

Users browsing this forum: No registered users and 3 guests