我正在用Python编写一个非常基本的Web代理。在它的当前状态我想要它做的就是从客户端获取请求并将其直接传递到Web,没有缓存或类似的东西。当我尝试接受来自Web服务器的响应时,我的问题出现了。我解析客户端HTTP请求以获取Web服务器的主机名,我转到请求的第二行并从那里提取名称。我的程序崩溃并显示错误消息 [Errno -5]没有与主机名关联的地址
我从Github中提取了一些相似的代码并运行了这些代码,他们似乎解析了HTTP请求的第一行并从网址中挖出了主机名,对我而言,这似乎是一个过于复杂的问题,但他们的代码相对较少好。我是从第二行采取换行符还是类似的东西?
import sys, socket
# Constants
PORT = 8080
MAX_BUFFER = 4096
HOST = 'localhost'
def main():
# Start socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(0)
print ('Proxy running on %s:%d' % (HOST, PORT))
except socket.error, (message):
print(message)
s.close()
sys.exit(1)
# Listen for requests
while 1:
# conn is the socket we can send and receive to/from the client
conn, client_addr = s.accept()
print('Got call from client')
request = conn.recv(MAX_BUFFER)
print(str(request))
# Parsing
first_line = request.split('\n')[0]
second_line = request.split('\n')[1]
url = first_line.split(' ')[1]
webserver = second_line.split(' ')[1]
print(webserver)
# Heard from client, now forward to server
try:
c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
c.connect((webserver, 80))
c.send(request)
print('Sent request to webserver')
while 1:
data = c.recv(MAX_BUFFER)
print('Received some data')
# while there is data to receive from server
if len(data) > 0:
conn.send(data)
print('Send data to client')
else:
print('break')
break
c.close()
conn.close()
except socket.error, (message):
print(message)
if c:
c.close()
if conn:
conn.close()
sys.exit(1)
print('Goodbye')
#******************End of main*********************
if __name__ == '__main__':
main()
以下是Github的代码摘录,它可以正常工作:
# Listen for requests
while 1:
# conn is the socket we can send and receive to/from the client
conn, client_addr = s.accept()
print('Got call from client')
request = conn.recv(MAX_BUFFER)
print(str(request))
# Parsing
first_line = request.split('\n')[0]
url = first_line.split(' ')[1]
http_pos = url.find('://')
if http_pos == -1:
temp = url
else:
temp = url[(http_pos + 3):]
port_pos = temp.find(':')
webserver_pos = temp.find('/')
if webserver_pos == -1:
webserver_pos = len(temp)
webserver = ''
port = -1
if port_pos == -1 or webserver_pos < port_pos:
port = 80
webserver = temp[:webserver_pos]
else:
port = int((temp[(port_pos + 1):])[:webserver_pos - port_pos -1])
webserver = temp[:port_pos]
print(webserver)
# Heard from client, now forward to server
信用:https://github.com/luugiathuy/WebProxyPython/blob/master/proxy.py