Skip to content

Instantly share code, notes, and snippets.

@BluCobalt
Created October 8, 2025 17:36
Show Gist options
  • Select an option

  • Save BluCobalt/11f544a7deea90a1838e4048e472bb6f to your computer and use it in GitHub Desktop.

Select an option

Save BluCobalt/11f544a7deea90a1838e4048e472bb6f to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import socket
import time
import errno
from datetime import datetime
HOST = "1.1.1.1"
PORT = 80
CHECK_INTERVAL = 5
LOG_FILE = "network_log.txt"
TIMEOUT = 3
def log_event(message):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
entry = f"{timestamp} - {message}\n"
with open(LOG_FILE, "a") as f:
f.write(entry)
print(entry, end="")
def check_connection():
try:
with socket.create_connection((HOST, PORT), timeout=TIMEOUT):
return True, None
except OSError as err:
if err.errno == errno.EHOSTUNREACH:
reason = "EHOSTUNREACH"
elif err.errno == errno.ENETUNREACH:
reason = "ENETUNREACH"
elif err.errno == errno.ETIMEDOUT:
reason = "ETIMEDOUT"
elif err.errno == errno.ECONNREFUSED:
reason = "ECONNREFUSED"
elif err.errno is not None:
reason = f"OS error {err.errno}: {err.strerror or err}"
else:
reason = f"Socket error: {err}"
return False, reason
def main():
last_status = None
down_since = None
log_event(f"Starting network monitor for {HOST}:{PORT}")
try:
while True:
online, error_reason = check_connection()
if online and last_status != "UP":
# We just came back online
if down_since:
downtime = time.time() - down_since
mins, secs = divmod(int(downtime), 60)
log_event(f"Network UP (downtime lasted {mins}m {secs}s)")
down_since = None
else:
log_event("Network UP")
last_status = "UP"
elif not online and last_status != "DOWN":
# We just went offline — log the cause once
log_event(f"Network DOWN ({error_reason})")
down_since = time.time()
last_status = "DOWN"
time.sleep(CHECK_INTERVAL)
except KeyboardInterrupt:
log_event("(KeyboardInterrupt)")
if last_status == "DOWN" and down_since:
downtime = time.time() - down_since
mins, secs = divmod(int(downtime), 60)
log_event(f"Network was DOWN on exit (down for {mins}m {secs}s)")
print("\nExiting gracefully. Log written to:", LOG_FILE)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment