4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ネットワークインタフェースに振られた IPv4 アドレスをコードで取得する (Linux)

4
Last updated at Posted at 2013-05-20

ただし ifconfig コマンドや ip コマンドの出力をパースするのはナシの方向で。

Linux だと ioctl(SIOCGIFADDR) で取れるそうです。

ほぼネタ元 (下記参考 1) のスクリプトそのままです。
Python だとディストリビューション付属の状態でここまで書けるので楽ですね。

import sys, socket, struct
from fcntl import ioctl

SIOCGIFADDR = 0x8915

if len(sys.argv) < 2:
  print >> sys.stderr, "Usage:", sys.argv[0], "<interface name>"
  sys.exit()

interface = sys.argv[1]

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
  ifreq  = struct.pack('16s16x', interface)
  ifaddr = ioctl(s.fileno(), SIOCGIFADDR, ifreq)
finally:
  s.close()

_, sa_family, port, in_addr = struct.unpack('16sHH4s8x', ifaddr)
print socket.inet_ntoa(in_addr)

参考

4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?