Ruby Tcpserver to Get Client Ip Address

Ruby TCPServer to get client ip address

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
^^^^^^

How to get Ip address of the request comming in Ruby TCP server?

See IPSocket#peeraddr.

p client.peeraddr(false)[3]

Or a bit more legibly:

address_family, port, hostname, numeric_address = client.peeraddr(false)
p numeric_address

Display the client IP address when an error occurs in SSLServer # accept

Socket#accept returns socket descriptor and addr_info, so you might do something like:

loop do
Thread.abort_on_exception = true
begin
_fd, @addr_info = @ssl_server.accept
Thread.start(_fd) do |socket|
do_something
socket.close
end
rescue => e
ERROR_LOGGER.error e
ERROR_LOGGER.info "AddrInfo: #{@addr_info}"
exit
end
end

How to get client IP and Server IP using Rails

Thanks: karim79 and Titanous.

Write the code in Controller

For Client IP:

request.remote_ip

@remote_ip = request.env["HTTP_X_FORWARDED_FOR"]

For Server IP:

require 'socket'

def local_ip
orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily

UDPSocket.open do |s|
s.connect '64.233.187.99', 1
s.addr.last
end
ensure
Socket.do_not_reverse_lookup = orig
end

Getting client IP from Ruby script through xinetd

After searching a lot for the solution, and even trying to ask on the #ruby channel on Freenode and being completely ignored, I've finally found the solution:

def to_ip(addr)
(4...8).map{|x|addr[x]}.join('.')
end

socket = Socket.for_fd(STDIN.fileno)
ip = to_ip(socket.getpeername)

Hope this helps someone!



Related Topics



Leave a reply



Submit