gintonik
Posts: 35
Joined: Fri Apr 22, 2016 4:09 pm

Check Network-Connection

Thu Jan 03, 2019 10:56 am

Hi,

i´m trying so resolve a solution for my little problem:

I had a System of two Pi´s who talk together. Everything works fine.
Now i want to try something like this:

When my System will be turned on both Pi´s are booting. My Router does the same.
Unfortunately the Router tooks a long time, maybe two Minutes before he is reachable and both Pi´s can talk together. Now i want to check up, when the System is workable and already started. Thats always when the Router is ready.

I think i need a endless loop who try to ping the Router "192.168.178.1".
When the Router is reachable the loop ends.

Something like this:

Code: Select all

connected = True
while connected:
    connected = subprocess.call(["ping", "192.168.178.1" , "-c 1"])
    
How can i get a True-Result as Answer from the Sub-Process? This is just an Example and doesn´t work!

gintonik
Posts: 35
Joined: Fri Apr 22, 2016 4:09 pm

Re: Check Network-Connection

Thu Jan 03, 2019 11:48 am

I found a solution, but it´s not the good way, because i used old os.system Function:

Code: Select all

result = True
while result:  
        result = os.system("ping -c 1 8.8.8.8 >/dev/null && echo 'Successfully pinged device!'")
        time.sleep(2)
        print(erg)
        
It´s really simple and it works!

My System ist not connected to the real Internet or some networks, it´s just talking together.

Now i can start/reboot my system anytime and get a message on my LED-Ticker, if it ready for use. That´s it!

hippy
Posts: 6210
Joined: Fri Sep 09, 2011 10:34 pm
Location: UK

Re: Check Network-Connection

Thu Jan 03, 2019 11:56 am

You could try a .popen() or, if you have a an IP service running on the other Pi you can try connecting to to it, check if you have or haven't -

Code: Select all

import socket

ADDR = "192.168.0.130"
PORT = 23

def CheckIfOnLine(addr,port):
  try:
    s = socket.create_connection((addr, port), 2)
    s.close()
    return True
  except:
    pass
  return False

if CheckIfOnLine(ADDR,PORT) : print("Okay - " + ADDR + " On-line")
else                        : print("FAIL - " + ADDR + " Off-line")

ghp
Posts: 1420
Joined: Wed Jun 12, 2013 12:41 pm
Location: Stuttgart Germany
Contact: Website

Re: Check Network-Connection

Thu Jan 03, 2019 12:49 pm


Return to “Python”