gpt-4o-mini-2024-07-18· OpenAI
WildChat-4.8M (AI2)
Write simple TCP forwarder in two directions on Ruby
- User
Write simple TCP forwarder in two directions on Ruby
- Assistant
Write simple TCP forwarder in two directions on Ruby
Creating a simple TCP forwarder in Ruby requires handling incoming TCP connections and forwarding data between the client and a target server. Below is an example of a TCP forwarder that forwards data in both directions.
This code will listen for incoming TCP connections on a specified port and forward the traffic to a target host and port.
require 'socket'
require 'thread'
class SimpleTcpForwarder
def initialize(local_port, target_host, target_port)
@local_port = local_port
@target_host = target_host
@target_port = target_port
end
def start
server = TCPServer.new(@local_port)
puts "Listening on port #{@local_port}..."
loop do
client = server.accept
puts "Client connected: #{client.peeraddr[2]}:#{client.peeraddr[1]}"
forward(client)
end
end
private
def forward(client)
target = TCPSocket.new(@target_host, @target_port)
# Create a thread to handle client to target communication
Thread.new do
begin
while data = client.gets # Read from client
target.puts(data) # Forward to target
end
rescue => e
puts "Error in client-to-target: #{e.message}"
ensure
target.close
end
end
# Handle target to client communication in the main thread
begin
while data = target.gets # Read from target
client.puts(data) # Forward to client
end
rescue => e
puts "Error in target-to-client: #{e.message}"
ensure
client.close
end
end
end
# Parameters
LOCAL_PORT = 1234 # Port to listen on
TARGET_HOST = 'example.com' # Target host
TARGET_PORT = 80 # Target port
# Start the forwarder
forwarder = SimpleTcpForwarder.new(LOCAL_PORT, TARGET_HOST, TARGET_PORT)
forwarder.start
tcp_forwarder.rb.LOCAL_PORT, TARGET_HOST, and TARGET_PORT constants accordingly.ruby tcp_forwarder.rb.Make sure you replace example.com and port values with your actual target server details. Additionally, ensure you have the appropriate permissions to bind to the specified local port.
Not yet included in a published release.