create a http server with a trace route in ruby

Here's an example of how to create an HTTP server with a trace route functionality in Ruby:

main.rb
require 'socket'
require 'traceroute'

# Define the HTTP response
def http_response
  "HTTP/1.1 200 OK\r\n" +
  "Content-Type: text/html\r\n" +
  "\r\n" +
  "<html><body><h1>Hello, World!</h1></body></html>\r\n"
end

# Create a new server instance
server = TCPServer.new('localhost', 8080)

# Listen for incoming connections
loop do
  client = server.accept

  # Get the client's IP address
  client_ip = client.peeraddr[3]

  # Perform a trace route to the client's IP address
  tracer = Traceroute.new(target: client_ip, max_hops: 30, protocol: 'udp')
  hops = tracer.trace.map { |hop| hop.ip_address }

  # Return the HTTP response with the trace route information
  response = "#{http_response}\r\n" +
             "<p>Trace Route to Client IP: #{client_ip}</p>\r\n" +
             "<ul>\r\n"

  hops.each do |hop|
    response += "<li>#{hop}</li>\r\n"
  end

  response += "</ul>\r\n\r\n"

  # Send the response back to the client
  client.puts(response)

  # Close the client connection
  client.close
end
1012 chars
43 lines

This code creates a new TCP server on localhost:8080, listens for incoming connections and then performs a trace route to the client's IP address each time a new connection is received. The results of the trace route are then included in the HTTP response that is sent back to the client.

gistlibby LogSnag