ふり返る暇なんて無いね

日々のメモ書きをつらつらと。メインブログに書くほどでもないことを流してます

自分のipアドレスを知りたいとき(linux)

最初に結論

hostname -Iを使うと良い

某所で、自ホストのIPアドレスを取得するためにこんなことをしている箇所を見つけたのが発端です。

LANG=C /sbin/ifconfig | grep 'inet addr' | awk '{print $2;}' | cut -d: -f2 | grep -v 127.0.0.1 | tail -n 1

もう少し、簡潔にできないかなー。(そもそもifconfigはもう使わない方が良いし) ip addr show eht0 とかでもデータ加工しないとだめだしな。とか考えてたら、hostnameでできそうだということが分かりました。

似たオプションで、-i-I があるのですが、名前解決ができるかできないかの違いです。用途に合わせて使い分けましょう。

   -i, --ip-address
          Display  the  network  address(es)  of the host name. Note that this works only if the
          host name can be resolved. Avoid using this option;  use  hostname  --all-ip-addresses
          instead.

   -I, --all-ip-addresses
          Display  all  network  addresses  of  the  host. This option enumerates all configured
          addresses on all network  interfaces.  The  loopback  interface  and  IPv6  link-local
          addresses are omitted. Contrary to option -i, this option does not depend on name res‐
          olution. Do not make any assumptions about the order of the output.