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
Deep Convert Openstruct to JSON
Encoding::Undefinedconversionerror: "\Xc2" from Ascii-8Bit to Utf-8
Algorithm to Shuffle an Array Randomly Based on Different Weights
Why Doesn't Array Override the Triple Equal Sign Method in Ruby
Failing to Enable User-Env-Compile on Heroku
Can a Ruby Module Be Described as a Singleton Class
How to Emit Yaml in Ruby Expanding Aliases
How to Effectively Force Minitest to Run My Tests in Order
Ssl_Connect Syscall Returned=5 Errno=0 State=Sslv3 Read Server Hello a (Openssl::Ssl::Sslerror)
Active Resource Complaining About Expects an Hash
Ruby on Rails - Add Condition on ':Include =>' to Load Limited Number of Objects
While Executing Gem ... (Argumenterror) Unknown Encoding Name - Cp720
How to Make Empty Tags Self-Closing with Nokogiri
Ruby on Rails: Create Confirmation View Before Creating the Object
How to Interpolate a Variable in a Ruby Regex