Ruby - Platform independent way to determine IPs of all network interfaces?

后端 未结 3 1924
难免孤独
难免孤独 2021-02-09 06:26

Is there an easy way in Ruby for me to get a list of the IP addresses for all network interfaces? It needs to work in Linux/Win/OSX and I\'d prefer to not have to parse ifconfi

3条回答
  •  暖寄归人
    2021-02-09 07:14

    As of Ruby 2.1, Socket#getifaddrs is available:

    001:0> require 'socket'
    => true
    002:0> Socket.getifaddrs.map { |i| i.addr.ip_address if i.addr.ipv4? }.compact
    => ["127.0.0.1", "192.168.1.121", "192.168.1.181"]
    

提交回复
热议问题