0

As the title. The reason why I want a native Ruby method is because I want the code portable across Linux and MacOS. "ip route show" can be used on Linux, but MacOS doesn't have "ip" command.

If there is not a native Ruby method, other portable method is also acceptable.

TieDad
  • 9,143
  • 5
  • 32
  • 58
  • Check the [`Socket`](https://ruby-doc.org/stdlib-2.2.4/libdoc/socket/rdoc/Socket.html#method-c-getaddrinfo) class should be able to get some useful information from there. – engineersmnky May 01 '17 at 13:35
  • http://stackoverflow.com/questions/6782658/how-to-get-default-gateway-in-mac-osx#7627059 may be possible to use this macos style – Garren S May 01 '17 at 13:41
  • Welcome to Stack Overflow. Please read "[ask]" and "[mcve]" and the linked pages and "[How much research effort is expected of Stack Overflow users?](http://meta.stackoverflow.com/questions/261592)". Your question isn't asked well. Did you search? If not why? If so, where and why didn't it help? Did you write code? If not, why? If so, what is the minimum code necessary to demonstrate the problem you're asking about? – the Tin Man May 01 '17 at 17:51

1 Answers1

0

I don't believe Socket can present you with the data you're looking for, but you can use netstat on MacOS and do platform detection to select between commands:

def gateway
  case Gem::Platform.local.os
  when "darwin" then `netstat -rn -f inet | grep 'default' | awk '{print $2}'`
  else `ip route | awk '/default/{print $3}'`
  end.chomp
end
coreyward
  • 77,547
  • 20
  • 137
  • 166
  • there can be multiple default, perhaps one of them has the lowest metrics. I think this one shold solve the problem: ip route | sort -nk 9 |awk '/default/{print $3; exit;}' – maxadamo Mar 26 '20 at 10:34