From: "Kristian Sørensen" Date: 2004-03-23T05:19:29+09:00 Subject: Re: Complete Ruby API? --------------090706080101000708070703 Content-Type: text/plain; charset=us-ascii; format=flowed Content-Transfer-Encoding: 7bit >> I am playing (just for fun) with a small webserver... For logging >> purposes, is there any way to get the IP address from the "remote" >> computer from a TCPSocket? > > Why didn't I just try ... socket.addr did the trick :) .... it actually didn't do the trick :-/ The socket.addr returns the local address of the ip-address. Do any of you know how to get the remote/connecting ip? (the actual server source is attached - 65 lines) Cheers! KS. --------------090706080101000708070703 Content-Type: text/plain; name="webserver.rb" Content-Transfer-Encoding: 7bit Content-Disposition: inline; filename="webserver.rb" #!/usr/bin/env ruby require "socket" trap(2) { exit 0 } class WebSession def initialize(connection) @connection = connection end def write(string) @connection.write(string) end def standardPage(title) write "HTTP/1.1 200 OK\r\n" write "Content-Type: text/html\r\n\r\n" write "#{title}\n" write "Welcome to KS Ruby Web!
download server source" write "" end end class WebServer def initialize() # to restrict to only accept local requests, use: .new("127.0.0.1" , 8080) @listen = TCPServer.new(8080); # if strange protocol-2 error: you have a running server allready! end def run loop { tcpsocket = @listen.accept puts tcpsocket.addr Thread.start(tcpsocket) { |aConnection| begin session = WebSession.new(aConnection) line = aConnection.gets.chomp puts "Request was: " + line file = line.split(/\s/).at(1).gsub("../","") if file =~ /^\/\w+/ fileOpen = "." + file File.open(fileOpen, "r") { |f| f.each { |line| session.write(line) } } else session.standardPage("KS Ruby Web") session.write("

Your request was:

\n" + line + "

Thank you for testing KS Ruby Web!") end ensure aConnection.close end } } end end WebServer.new().run --------------090706080101000708070703--