LoginSignup
1
2

More than 5 years have passed since last update.

line monitor > 情報表示部分 (151125) > IPアドレスを取得するpython実装

Last updated at Posted at 2015-11-24

line monitor
http://qiita.com/7of9/items/028556c5a819a6a8de96

動作確認
CentOS 6.5

IPアドレスの4つ目の3桁を7セグLEDで表示したい。そのため、pythonからIPアドレスを取得する。

try1

参考
http://qiita.com/fukkyy/items/8872944406c6dedfe34b

151125a.py
import socket

ipadr = socket.gethostbyname(socket.gethostname())
print ipadr

上記を実行してみると

結果
[toLearn]$ python 151125a.py 
127.0.0.1

ループバックの方が取れてしまった。
タイトルが「ローカルのipアドレスを取得」で納得。

欲しいのは192.168.の方。

try2

参考 SO

151125b.py
import socket
import fcntl
import struct

def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
        s.fileno(),
        0x8915,  # SIOCGIFADDR
        struct.pack('256s', ifname[:15])
    )[20:24])

ipadr = get_ip_address('eth0')  # '192.168.xxx.xxx'
print ipadr
実行結果
[toLearn]$ python 151125b.py 
192.168.10.8

他にimport netifacesを使う方法もあるが、CentOS6.5で試したところエラーが出た。
パッケージが不要の上記の方法でできるので、こちらのほうがいい。

1
2
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
1
2