|
| 1 | +## TCP Second Try ## |
| 2 | +## Component Connect to other Machine ## |
| 3 | + |
| 4 | +import socket |
| 5 | +import sys |
| 6 | +import re |
| 7 | +def validate(Type, data): |
| 8 | + ip = re.compile("^[0-9]{1,3}[.]{1}[0-9]{1,3}[.]{1}[0-9]{1,3}[.]{1}$") |
| 9 | + |
| 10 | + if Type == 'ip': |
| 11 | + if ip.match(data): |
| 12 | + return True |
| 13 | + else: |
| 14 | + return False |
| 15 | + |
| 16 | + else: |
| 17 | + return "No Type: "+Type |
| 18 | + |
| 19 | +#if domain name is sent then it is resolved here |
| 20 | +def domain(host): |
| 21 | + try: |
| 22 | + remote_ip = socket.gethostbyname(host) |
| 23 | + return remote_ip |
| 24 | + |
| 25 | + except socket.gaierror: |
| 26 | + print("Host name could not be resolved") |
| 27 | + return False |
| 28 | +def create(): |
| 29 | + try: |
| 30 | + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 31 | + return s |
| 32 | + except socket.error: |
| 33 | + print("Failed to connect") |
| 34 | + return False |
| 35 | + |
| 36 | +def connect(remote_ip, port): |
| 37 | + |
| 38 | + |
| 39 | + if not validate('ip', remote_ip): |
| 40 | + remote_ip = domain(remote_ip) |
| 41 | + |
| 42 | + print("Connecting to: " + remote_ip+" Port:",port) |
| 43 | + try: |
| 44 | + s.connect((remote_ip, port)) |
| 45 | + |
| 46 | + |
| 47 | + except NameError: |
| 48 | + try: |
| 49 | + s = create() |
| 50 | + s.connect((remote_ip, port)) |
| 51 | + |
| 52 | + except ConnectionRefusedError: |
| 53 | + print("Connection Refused Error (likely because other machine's port isn't open)") |
| 54 | + return False |
| 55 | + |
| 56 | + except ConnectionRefusedError: |
| 57 | + print("Connection Refused Error (likely because other machine's port isn't open)") |
| 58 | + return False |
| 59 | + |
| 60 | + except: |
| 61 | + print("Unknown Error") |
| 62 | + return False |
| 63 | + print("Socket connected to IP: " + remote_ip) |
| 64 | + return True |
| 65 | +connect("127.0.0.1", 80) |
0 commit comments