As the title says. I have confirmed the operation on windows and mac. You can get it as an array.
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:
#other than that
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
Recommended Posts