Python HTTP proxy Raw Sockets -


i'm trying implement http proxy using raw sockets. idea getting request client , sending request server , getting response , , sending client. looks easy have been trying figuring out 2 days. here response gets corrupted . :)

import socket import sys import requests  def merr(requesti):     hosti = requesti.split("host: ")     hosti = hosti[1]     hosti = hosti.split("user-agent: ")     hosti = hosti[0]     hosti = hosti.strip()     return hosti  def merr_buff(data):     try:         temp = requesti.split("content-length:")         temp = temp[1]         temp = temp.split("\n")         temp = temp[0]         temp = temp.replace(" ","")         print temp         return temp     except:         pass    def dergo(requesti, hosti):     s = socket.socket(socket.af_inet, socket.sock_stream)     s.connect((hosti, 80))     s.send(str(requesti))     print requesti     fdx = s.recv(10000)     return str(fdx)   def bind():     host = ''        port = 8080       s = socket.socket(socket.af_inet, socket.sock_stream)     s.setsockopt(socket.sol_socket, socket.so_reuseaddr, 1)      print 'socket created'      try:         s.bind((host, port))     except socket.error , msg:         print 'bind failed. error code : ' + str(msg[0]) + ' message ' + msg[1]         sys.exit()      print 'socket bind complete'      s.listen(200)         print 'socket listening'      conn, addr = s.accept()       while 1:         data = conn.recv(32000)         if(data != ''):              if(data.find("http/1.1") != -1):                   target = merr(data)                 print  target                 response = dergo(data,target)                 conn.send(response)                 print "u dergua"                  conn.close()                 conn, addr = s.accept()         s.close()   bind() 

you don't specify how response corrupt, here problems noticed code.

when sending data, socket.send may not send whole string, return number of bytes transmitted. instead use socket.sendall attempt send whole string.

similarly when receiving data socket, socket.recv receive up to buffer size specified, may not full content of connection. should keep calling socket.recv until return value evaluates false, example (taken docs):

while 1:     data = conn.recv(1024)     if not data: break     conn.sendall(data) conn.close() 

try making these changes in software , report back.


Comments

Popular posts from this blog

node.js - Using Node without global install -

How to access a php class file from PHPFox framework into javascript code written in simple HTML file? -

java - Null response to php query in android, even though php works properly -