LoginSignup
7
5

More than 3 years have passed since last update.

Pythonで自身のIPアドレスを取得

Last updated at Posted at 2020-08-21

表題の通りです。 windowsとmacでは動作確認しました。
配列で取得出来ます。

パッケージインストール

pip install psutil
pip install netifaces

スクリプト

import netifaces as ni
import psutil
import os
import socket


def get_ip() -> list:
    if os.name == "nt":
        # Windows
        return socket.gethostbyname_ex(socket.gethostname())[2]
        pass
    else:
        # それ以外
        result = []
        address_list = psutil.net_if_addrs()
        for nic in address_list.keys():
            ni.ifaddresses(nic)
            try:
                ip = ni.ifaddresses(nic)[ni.AF_INET][0]['addr']
                if ip not in ["127.0.0.1"]:
                    result.append(ip)
            except KeyError as err:
                pass
        return result


print(get_ip())

結果

['192.168.XXX.XXX', '10.211.XX.X', '10.37.XXX.X']

参考サイト

https://stackoverflow.com/questions/24196932/how-can-i-get-the-ip-address-from-nic-in-python
https://stackoverflow.com/questions/3837069/how-to-get-network-interface-card-names-in-python
https://edosha.hatenablog.jp/entry/2017/08/09/150636

7
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
7
5