Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A trivial HTTP proxy server for testing and troubleshooting
# This is a trivial HTTP proxy server, intended for use as a troubleshooting tool
# ONLY (not for real, actual, production use). I wrote this because I couldn't find
# a simple HTTP proxy that I could use to test HTTP proxy support in Net::SSH.
#
# This code is in the public domain, so do with it what you will!
require 'socket'
port = ARGV.shift || 8080
address = ARGV.shift || "127.0.0.1"
puts "starting proxy on #{address}:#{port}"
server = TCPServer.new(address, port)
loop do
client = server.accept
request = client.readline
headers = {}
loop do
line = client.readline.strip
break if line.empty?
key, value = line.split(/:\s*/, 2)
headers[key.downcase] = value
end
if request =~ /^CONNECT (.*?):(\d+) HTTP/
host = $1
port = $2.to_i
puts "proxying to #{host}:#{port}"
client.write "HTTP/1.0 200 OK\r\n\r\n"
proxy = TCPSocket.new(host, port)
loop do
r, = IO.select([client, proxy])
if r.include?(client)
data = client.recv(1024)
break if data.nil? || data.empty?
proxy.write(data)
end
if r.include?(proxy)
data = proxy.recv(1024)
break if data.nil? || data.empty?
client.write(data)
end
end
proxy.close
else
puts "not a CONNECT request #{request.inspect}"
end
client.close
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.