Skip to content

Instantly share code, notes, and snippets.

@safeith
Last active October 2, 2020 13:20
Show Gist options
  • Save safeith/b9e2d4addf22713eb880b77d3dc990d1 to your computer and use it in GitHub Desktop.
Save safeith/b9e2d4addf22713eb880b77d3dc990d1 to your computer and use it in GitHub Desktop.
Simple TCP socket in Python that accepts URL(s) as input and return its http status code
#!/usr/bin/env python3
import socket
import requests
def url_status(listening_ip, listening_port, *args, **kwargs):
"""
This a simple TCP socket that accept url(s) as input and return url(s), and
its status code.
Args:
listening_ip (str): Binding IP
listening_port str: Binding port
*args: Variable length argument list
**kwargs: Arbitrary keyword arguments:
status_log (str): Path of status log
error_log (str): Path of error log
"""
status_log = kwargs['status_log'] if 'status_log' in kwargs else 'status.log'
error_log = kwargs['error_log'] if 'error_log' in kwargs else 'error.log'
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((listening_ip, listening_port))
sock.listen(5)
while True:
connection, address = sock.accept()
buf = connection.recv(1024)
connection.send(buf)
urls = buf.decode().strip().split("\n")
for url in urls:
try:
req = requests.get(url)
except Exception as e:
with open(error_log, 'a') as error_log_file:
error_log_file.write(f'{url}, {e}\n')
connection.send(
f' => {url} is not reachable\n'.encode())
continue
else:
with open(status_log, 'a') as status_log_file:
status_log_file.write(f'{url},{req.status_code}\n')
connection.send(
f' => {url} status code is {req.status_code}\n'.encode())
connection.close()
url_status('127.0.0.1', 8080)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment