Skip to content

Instantly share code, notes, and snippets.

@fornellas
Created July 12, 2016 16:38
Show Gist options
  • Save fornellas/c70263ebec580a0496996caf78c912b7 to your computer and use it in GitHub Desktop.
Save fornellas/c70263ebec580a0496996caf78c912b7 to your computer and use it in GitHub Desktop.
Print TCP connection traffic to stdout.
#!/usr/bin/env ruby
require 'socket'
require 'thwait'
unless ARGV.size == 2
STDERR.puts "Usage: #{$PROGRAM_NAME} listen_address:listen_port target_address:target_port"
exit 1
end
listen_address, listen_port = ARGV.shift.split(':')
target_address, target_port = ARGV.shift.split(':')
def read_and_write prefix, from, to
Thread.new do
from.each do |line|
puts "#{prefix} #{line}"
STDOUT.flush
to.write(line)
to.flush
end
end
end
puts "Listening on #{listen_address}:#{listen_port}..."
tcp_server = TCPServer.new(listen_address, listen_port)
loop do
client = tcp_server.accept
addr_family, port, hostname, numeric_addr = *client.addr(true)
puts "New connection from #{hostname} (#{numeric_addr}:#{port})."
puts "Connecting to #{target_address}:#{target_port}."
target_socket = TCPSocket.new(target_address, target_port)
client_thread = read_and_write("<", client, target_socket)
target_thread = read_and_write(">", target_socket, client)
client_thread.join
puts "Closing connection from #{hostname} (#{numeric_addr}:#{port})."
client.close
target_socket.close
target_thread.join rescue IOError
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment