【问题标题】:How to get Ip address of the request comming in Ruby TCP server? [duplicate]如何获取来自 Ruby TCP 服务器的请求的 IP 地址? [复制]
【发布时间】:2020-03-14 12:44:24
【问题描述】:
我已经编写了一个代码以在 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
【问题讨论】:
标签:
ruby-on-rails
ruby
tcp
tcpclient
【解决方案1】:
见IPSocket#peeraddr。
p client.peeraddr(false)[3]
或者更清楚一点:
address_family, port, hostname, numeric_address = client.peeraddr(false)
p numeric_address
【解决方案2】:
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