Skip to content

Instantly share code, notes, and snippets.

@zerolagtime
Created May 15, 2024 01:24
Show Gist options
  • Save zerolagtime/9936bf84cf8a65b5f70d6b666993b98d to your computer and use it in GitHub Desktop.
Save zerolagtime/9936bf84cf8a65b5f70d6b666993b98d to your computer and use it in GitHub Desktop.
Test a TCP socket connection in Python
import socket
import sys
"""
Usage: python3 test_tcp_socket.py [host [port]]
Where host can be a string or IPv4 address. Port defaults to 80.
"""
host = sys.argv[1] if len(sys.argv)>1 and sys.argv[1] \
else "example.com"
port = int(sys.argv[2]) if len(sys.argv)>2 and sys.argv[2] else 80
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.settimeout(3)
s.connect((host, port))
print(f"Successfully connected to {host}:{port}")
except Exception as e:
print(f"Failed! {e}")
s.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment