Hopefully this doesn't seem like shit posting. This is something I put together this morning, and I'm looking for some more ideas on what to do with this. Fr those of you who can't make sense of simple code, what this does is listen on whatever port you tell it to and then logs all IP addresses that connect to it in a file. When the client connects it prints the client's IP address to the client. It's like a What'sMyIP server. Just fire this server up and enter the IP and port into your URL on the client. Here's the code:
#!/usr/bin/env ruby
require 'socket' # We need this shit
# Build the socket
server = TCPServer.new(ARGV[0])
# Begin for exception handling
begin
loop do # Keep server alive
Thread.new(server.accept) do |c| # Threaded for simultaneus connections
# Prints requests to server for debugging
request = c.gets
STDERR.puts request
# The whole point of this script
res = "Your IP address is: #{c.peeraddr[2]}\n"
# Build a proper HTTP response
# Be sure to include required whitespacing
c.print "HTTP/1.1 200 OK\r\n" +
"Content-Type: text/plain\r\n" +
"Content-Length: #{res.bytesize}\r\n" +
"Connection: close\r\n"
c.print "\r\n"
c.print res # Print the actual response
# Logs connecting clients IP addresses to a file
# Saves the exact time of connection
# Appends logs
File.open("iplog.txt", "a") do |log|
log.puts "Connection from #{c.peeraddr[2]} logged at: #{Time.new}"
end
# Close that shit
c.close
end
end
# Gets rid of ugly error messages with Ctrl-C
rescue Interrupt
puts " Connection terminated"
end
The only trouble I am having is that the exception for SocketError doesn't actually go into effect. It posts the actual Ruby error instead of the output I specified. Not a huge deal really, but I've done it plenty of times before successfully. I'm looking for ways to further this code.
EDIT: Almost forgot. Here's the client code if you want to try it via command-line. I just stole this from a Rubydoc website because it wasn't my focus and it's extremely simple code.
#!/usr/bin/env ruby
require 'socket'
req = "GET / HTTP/1.0\r\n\r\n"
s = TCPSocket.new ARGV[0], ARGV[1]
s.print(req)
res = s.read
headers, body = res.split("\r\n\r\n", 2)
print body
Note: The server only works on port 1023 and above.