-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtcp.py
121 lines (94 loc) · 2.88 KB
/
tcp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
## TCP Easy Setup Module v0.9##
## Component Connect to other Machine ##
## R. M. Jones ##
import socket
import sys
import re
def validate(Type, data):
ip = re.compile("^[0-9]{1,3}[.]{1}[0-9]{1,3}[.]{1}[0-9]{1,3}[.]{1}$")
if Type == 'ip':
if ip.match(data):
return True
else:
return False
else:
return "No Type: "+Type
#if domain name is sent then it is resolved here
def domain(host):
try:
remote_ip = socket.gethostbyname(host)
return remote_ip
except socket.gaierror:
print("Host name could not be resolved")
return False
def getmyip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("1.1.1.1", 80))
TCP_IP = s.getsockname()[0]
s.close()
return TCP_IP
#The default ip is your local one and port is 5050
def bind(TCP_IP=getmyip(), TCP_PORT=5050):
try:
s = create()
s.bind((TCP_IP, TCP_PORT))
print("Ready to connect on: "+TCP_IP+" on port:", TCP_PORT)
except OSError:
print("Cannot connect please check your PC")
exit()
except:
print("Ready to connect on: "+TCP_IP+" on port:", TCP_PORT)
s.listen(1)
conn, addr = s.accept()
print ('Connection address:', addr)
return conn
def create():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
return s
except socket.error:
print("Failed to connect")
return False
def connect(remote_ip, port):
if not validate('ip', remote_ip):
remote_ip = domain(remote_ip)
if remote_ip == False:
print("Error Resolving Host name")
return False
print("Connecting to: " + remote_ip+" Port:",port)
try:
s.connect((remote_ip, port))
except NameError:
try:
s = create()
s.connect((remote_ip, port))
except ConnectionRefusedError:
print("Connection Refused Error (likely because other machine's port isn't open)")
return False
except TimeoutError:
print("Connection timed out")
return False
except ConnectionRefusedError:
print("Connection Refused Error (likely because other machine's port isn't open)")
return False
except:
print("Unknown Error")
return False
print("Socket connected to IP: " + remote_ip)
return s
def send(data, s):
try:
s.sendall(data.encode())
return True
except:
print("Couldn't send data")
return False
def receive(s, buff=4069):
try:
return s.recv(buff).decode()
except ConnectionResetError:
print("Error ConnectionResetError")
return False
except ConnectionAbortedError:
print("Error ConnectionAbortedError")
return False