Skip to content

Instantly share code, notes, and snippets.

@kjunichi
Last active August 29, 2015 14:05
Show Gist options
  • Save kjunichi/464fd03dfef18936d004 to your computer and use it in GitHub Desktop.
Save kjunichi/464fd03dfef18936d004 to your computer and use it in GitHub Desktop.
ローカルIPアドレスを取得するには

はじめに

Dockerで音を鳴らすという記事を書いた際に、Dockerコマンドを実行しているホストのローカルIPアドレスの取得方法が 気になり、最近使っている言語のいくつかでどうやって書くのか調べた。

Ruby

2.1以降

ruby -r socket -e 'puts Socket.getifaddrs.select{|x| x.name == "eth0" and x.addr.ipv4?}.first.addr.ip_address'

Link

Python

python -c "import socket;print([(s.connect(('8.8.8.8', 80)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1])"
pip install netifaces
python -c "import netifaces;print(netifaces.ifaddresses('eth0')[netifaces.AF_INET][0]['addr'])"

Link

Perl

cpanm install IO::Interface
perl -MIO::Interface::Simple -e 'CORE::say IO::Interface::Simple->new(shift || "eth0")->address'

Link

AppleScript

IPv4 address of (get system info)

Link

Node.js

node -e  "require('os').networkInterfaces()['eth0'].filter(function(elm){if(elm.family=='IPv4')console.log(elm.address)})"
node -e "require('os').networkInterfaces()['ローカル エリア接続'].filter(function(elm){if(elm.family=='IPv4') console.log(elm.address)})"

Link

シェル

hostname -I

まとめ

意外と、ローカルIPアドレスの取得は難しいことが分かった。多くの言語は別途モジュール等をインストールして それを使って書くのがスマートでプラットフォーム依存が低く抑えられる感じだった。

残念ながら、ここに上げた書き方でどんな環境でもOKかというとそんなことは無いので、必要に応じて微調整が必要。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment