如何在Ruby TCP服务器中获取请求通信的Ip地址



我已经用Ruby编写了一个接收TCP请求的代码,但我无法获得即将到来的请求的Ip地址
我的代码是:

require 'socket'
puts "Starting the Server..................."
server = TCPServer.new 53492 # Server bound to port 53492
loop do
Thread.start(server.accept) do |client|
# client = server.accept # Wait for a client to connect
# client.puts "Hello you are there!"
result = ''
ansiString = client.recv(100).chomp
p "String = #{ansiString}"
begin
#  How to get the request IP adress here
rescue Errno::EPIPE
puts "Connection broke!"
end
end
end

参见IPSocket#peeraddr

p client.peeraddr(false)[3]

或者更清晰一点:

address_family, port, hostname, numeric_address = client.peeraddr(false)
p numeric_address
require 'socket'
puts "Starting the Server..................."
server = TCPServer.new 53492 # Server bound to port 53492
loop do
Thread.start(server.accept) do |client|
# client = server.accept # Wait for a client to connect
# client.puts "Hello you are there!"
p "Client address = #{client.peeraddr[3]}"  ## Answer
result = ''
ansiString = client.recv(100).chomp
p "String = #{ansiString}"
begin
#  How to get the request IP adress here
rescue Errno::EPIPE
puts "Connection broke!"
end
end
end

最新更新