Last active
July 23, 2017 15:20
-
-
Save psidex/f464c32597c7cc77ab30e027b86694cc to your computer and use it in GitHub Desktop.
Helps test if server & client machines can connect
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import socket | |
import sys | |
host = input("Host >> ") | |
port = int(input("Port >> ")) | |
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
try: | |
s.connect((host, port)) | |
except OSError: | |
print("Socket attempted to connect to an unreachable network") | |
except ConnectionRefusedError: | |
print("No connection could be made") | |
print("Connected to {}:{}".format(host, port)) | |
while 1: | |
try: | |
msg = input("\nMessage: ") | |
print("Sending message...") | |
s.send(str.encode(msg)) | |
print("Message sent, waiting for response...") | |
data = s.recv(1024) | |
print("Data recieved, decoding...") | |
decoded = data.decode("utf-8") | |
print("Message recieved from server:") | |
print(decoded) | |
except (ConnectionResetError, OSError, KeyboardInterrupt): | |
print("Exception occurred, closing connection...") | |
s.close() | |
sys.exit() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import socket | |
import sys | |
import threading | |
host = input("Host >> ") | |
port = int(input("Port >> ")) | |
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
def client_handler(client, addr): | |
ip_port = "{}:{}".format(addr[0], addr[1]) | |
while True: | |
try: | |
r_msg = client.recv(1024) | |
if r_msg: | |
decoded = r_msg.decode("utf-8") | |
print("\nRecieved message") | |
print("{} -> {}".format(ip_port, decoded)) | |
print("Echoing...") | |
print("{} -> {}".format(decoded, ip_port)) | |
try: | |
client.send(str.encode(decoded)) | |
print("Sent") | |
except (BrokenPipeError, OSError): | |
raise ConnectionResetError | |
except (ConnectionResetError, ConnectionAbortedError, OSError): | |
client.close() | |
print("[*] Client {} dropped".format(ip_port)) | |
try: | |
s.bind((host, port)) | |
except OSError: | |
print("[!] Unable to bind to port {}".format(port)) | |
sys.exit() | |
print("[!] Socket bound") | |
s.listen(5) | |
print("[!] Socket listening on {}:{}".format(host, port)) | |
while True: | |
try: | |
client, addr = s.accept() | |
except OSError: | |
pass | |
except KeyboardInterrupt: | |
s.close() | |
sys.exit() | |
else: | |
print("\n[*] Accepted connection from: {}:{}".format(addr[0], addr[1])) | |
threading.Thread(target=client_handler, args=(client, addr)).start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment