Page 1 of 1

Pi to Pi connection checker

Posted: Sat Oct 04, 2014 8:08 pm
by jdeeewp
Hello,

I have two Pi at two different addresses monitoring all sorts of things.
I would like each to check in with the other to ensure connectivity and in the event of a power failure, network failure, etc... alert me with my existing alerting system.

my first thought was to have them email each other periodically but i would haven't really looked into code to check emails and verify its from the other pi.

I then looked into establishing a socket connection between the two and landed on the following setup.
Are there any other neat ways to do this?

It basically attempts a connection and alerts me if unsuccessful. I figure there is no point in sending/receiving stuff due to security concerns. There would be instances of server and client running on each Pi.
Thanks!

'Server' Side

Code: Select all

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #create socket
s.bind(('', 12345)) #bind port
s.listen(1) #set to listen

while 1:
	conn, addr = s.accept() #accept connection
	Logit(str(addr)) # Custom log function
	conn.close() #close connection
'Client' Side

Code: Select all

import socket

while 1:
	try:
		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # create socket
		s.connect((mydns.dyndns.com, 12345)) # connect
		s.close() # close socket
	except socket.error:	#catch socket error (failed connection)
		sendalert('mydns.dyndns.com not reachable!') 	#personal alert function

	time.sleep(3600) #try again later
Disclaimer: This is condensed code. I have logic to handle repetitive alerts and also logic to alert when connection has resumed from failure among other things.

Re: Pi to Pi connection checker

Posted: Sat Oct 04, 2014 8:43 pm
by DougieLawson
On pi
ping -c3 raspberry.local

On raspberry
ping -c3 pi.local

works to prove both are connected to the router.

If I want an ad-hoc communications stream I'll use netcat (aka nc) or ssh.

It's easier than writing my own socket code.

If I'm running an MQTT broker somewhere in my network I would use that to send a periodic heartbeat message.

Re: Pi to Pi connection checker

Posted: Sun Oct 05, 2014 2:22 pm
by jdeeewp
Heartbeat message was exactly what i was thinking however I am not running MQTT at the moment. After a few searches this appears to be a better alternative then a socket connection. Considering i would be able to send status messages around this may be useful as i continue to setup net connected things.

Since these pi's will be at different networks across the internet pinging from outside the network will only confirm the gateway is connected right?

I will start looking into SSH or netcat and see what those offer.

perhaps a similar approach using SSH and paramiko for python? (try connection?)