-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path07_socket_error.py
More file actions
54 lines (47 loc) · 1.61 KB
/
07_socket_error.py
File metadata and controls
54 lines (47 loc) · 1.61 KB
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
import sys
import socket
import argparse
def main():
# setup argument parsing
parser = argparse.ArgumentParser(description='Socket Error Examples')
parser.add_argument('--host', action="store", dest="host", required=False)
parser.add_argument('--port', action="store", dest="port", type=int, required=False)
parser.add_argument('--file', action="store", dest="file", required=False)
given_args = parser.parse_args()
host = given_args.host
port = given_args.port
filename = given_args.file
# First try-except block -- create socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error as e:
print ("Error creating socket: %s" % e)
sys.exit(1)
# Second try-except block -- connect to given host/port
try:
s.connect((host, port))
except socket.gaierror as e:
print("Address-related error connecting to server: %s" % e)
sys.exit(1)
except socket.error as e:
print ("Connection error: %s" % e)
sys.exit(1)
# Third try-except block -- sending data
try:
s.sendall("GET %s HTTP/1.0\r\n\r\n" % filename)
except socket.error as e:
print("Error sending data: %s" % e)
sys.exit(1)
while 1:
# Fourth tr-except block -- waiting to receive data from remote host
try:
buf = s.recv(2048)
except socket.error as e:
print("Error receiving data: %s" % e)
sys.exit(1)
if not len(buf):
break
# write the received data
sys.stdout.write(buf)
if __name__ == '__main__':
main()