Skip to content

Instantly share code, notes, and snippets.

@pavelanni
Last active January 20, 2018 20:30
Show Gist options
  • Save pavelanni/51882888789251ba059679ccd94de641 to your computer and use it in GitHub Desktop.
Save pavelanni/51882888789251ba059679ccd94de641 to your computer and use it in GitHub Desktop.
This Raspberry Pi script pings a specific host and if it's up it turns the LED on
#!/usr/bin/env python3
#
# This script pings a site specified in the command line and
# turns the LED on if the site is on. It should be run as root because
# it uses sockets in the ping implementation below.
#
# Code for ping below is borrowed from https://gist.github.com/pyos/10980172
#
import time
import random
import struct
import select
import socket
import sys
from gpiozero import LED
from time import sleep
LED_PIN = 17
def chk(data):
x = sum(x << 8 if i % 2 else x for i, x in enumerate(data)) & 0xFFFFFFFF
x = (x >> 16) + (x & 0xFFFF)
x = (x >> 16) + (x & 0xFFFF)
return struct.pack('<H', ~x & 0xFFFF)
def ping(addr, timeout=1, number=1, data=b''):
with socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) as conn:
payload = struct.pack('!HH', random.randrange(0, 65536), number) + data
conn.connect((addr, 80))
conn.sendall(b'\x08\0' + chk(b'\x08\0\0\0' + payload) + payload)
start = time.time()
while select.select([conn], [], [], max(0, start + timeout - time.time()))[0]:
data = conn.recv(65536)
if len(data) < 20 or len(data) < struct.unpack_from('!xxH', data)[0]:
continue
if data[20:] == b'\0\0' + chk(b'\0\0\0\0' + payload) + payload:
return time.time() - start
if __name__ == '__main__':
if (len(sys.argv) < 2):
print ("Usage: " + sys.argv[0] + " <address>")
exit(1)
led = LED(LED_PIN)
while True:
if (bool(ping(sys.argv[1]))):
led.on()
else:
led.off()
sleep(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment