I want to get the client IP address in TCPServer in Ruby. And (if possible) the MAC address.
For example, a time server in Ruby, see the comment.
tcpserver = TCPServer.new("", 80) if tcpserver puts "Listening" loop do socket = tcpserver.accept if socket Thread.new do puts "Connected from" + # HERE! How can i get the IP Address from the client? socket.write(Time.now.to_s) socket.close end end end end
Many thanks!
Ruby 1.8.7:
>> fam, port, *addr = socket.getpeername.unpack('nnC4') => [4098, 80, 209, 191, 122, 70] >> addr => [209, 191, 122, 70] >> addr.join('.') => "209.191.122.70"
Ruby 1.9 makes it simpler:
>> port, ip = Socket.unpack_sockaddr_in(socket.getpeername) => [80, "209.191.122.70"] >> ip => "209.191.122.70"
Use socket.addr:
socket.addr
irb(main):011:0> socket.addr => ["AF_INET", 50000, "localhost", "127.0.0.1"]
It returns an array showing the type of socket, port, and host information.
MAC-, , , . MAC-, "" . MAC-, arp . , , , MAC- .