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

后端 未结 3 1981
难免孤独
难免孤独 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:20

    I don't think ruby has a standard api for this but under some assumptions this should be fairly reliable across platforms:

    require 'socket'
    Socket::getaddrinfo(Socket.gethostname, 'echo', Socket::AF_INET).map { |x| x[3] }
    

    Here we are assuming quite a few things like the machine having a local hostname pointing to the correct ip addresses. So, this is definitely not completely reliable but it's platform independent and works on the common setups.

    Edit: If you decide to get down to parsing ifconfig, consider forking ruby-ifconfig. It claims to do that on most non-windows platforms already.

提交回复
热议问题