a0rtega
a0rtega

Reputation: 315

In TCPServer (Ruby) how can i get the IP/MAC from the client?

i want to get the IP Address of the client in a TCPServer in Ruby. And (if it is 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

Thank you very much!

Upvotes: 5

Views: 6294

Answers (2)

Eric Dennis
Eric Dennis

Reputation: 2096

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 a little more straightforward:

>> port, ip = Socket.unpack_sockaddr_in(socket.getpeername)
=> [80, "209.191.122.70"]
>> ip
=> "209.191.122.70"

Upvotes: 8

ctennis
ctennis

Reputation: 207

Use 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, the port, and the host information.

Regarding finding the MAC address, I don't know of anyway that's built in. If you want the local MAC address, you can use Ara Howard's "macaddr" gem. If you want the remote MAC address, you can use the command line arp program and parse its output. Note that this will only be valid if the remote machine is on the same local network, as MAC addresses are not transmitted across non-local networks.

Upvotes: 5

Related Questions