assignment 12.1

修改套接字程序socket1.py, 提示用户输入URL, 让它可以读取任何网页。 你可以使用split(’/’)拆分URL, 抽取出套接字connect调用的主机名。 使用try和except增加错误检查, 处理用户输入不恰当的网址或不存在的URL这两种情况

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import socket
import re

url = raw_input('Enter - ')
if (re.search('^http://[a-zA-Z0-9]+.[a-zA-Z0-9]+.[a-zA-Z0-9]+/',url)):
words = url.split('/')
host = words[2]
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
mysock.connect((host, 80))
except:
print 'is not a correct web server'
exit()
mysock.send(str.encode('GET ' + url + ' HTTP/1.0nn'))
while True:
data = mysock.recv(512)
if ( len(data) < 1 ) :
break
print data;

mysock.close()
else:
print('The URL that you input is bad format')