Ba7a7chy
Ba7a7chy

Reputation: 1521

Ruby TCPServer to get client ip address

This is my not working script (just hangs...)

require 'socket'
server = TCPServer.new 2000

loop do
  Thread.start(server.accept) do |client|
    sock_domain, remote_port, remote_hostname, remote_ip = server.peeraddr
    client.puts "Hello !"
    client.puts "Time is #{Time.now}"
    puts "connection coming from #{remote_ip} and port #{remote_port}"
    client.close
  end
end

I want to have an output of the connecting client IP but the connection is made and nothing happens.

Upvotes: 3

Views: 4647

Answers (1)

Casper
Casper

Reputation: 34308

Code is fine, except this:

sock_domain, remote_port, remote_hostname, remote_ip = server.peeraddr

Should be this:

sock_domain, remote_port, remote_hostname, remote_ip = client.peeraddr
                                                       ^^^^^^

Upvotes: 7

Related Questions