I've been reading about the following solutions here, but it only works for one IP Address only. I'm not able to print the rest of the IPs (multiple network/wireless cards).
References
C:\>ipconfig | findstr IPv4
IPv4 Address. . . . . . . . . . . : 192.168.1.1
IPv4 Address. . . . . . . . . . . : 192.168.5.1
C:\>python
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import socket
>>> print (socket.gethostbyname(socket.gethostname()))
192.168.5.1
>>>
Please let me know how to print all IP Addresses in Python.
Update 1:
As suggested by Rahul, I've tried the following code but it didn't return anything on the screen.
c:\Python\Codes>more ip.py
from netifaces import interfaces, ifaddresses, AF_INET
def ip4_addresses():
ip_list = []
for interface in interfaces():
for link in ifaddresses(interface)[AF_INET]:
ip_list.append(link['addr'])
return ip_list
c:\Python\Codes>
c:\Python\Codes>ip.py
c:\Python\Codes>
Update 2:
I've also tried Elemag's code as suggested here. It works on Python interpreter but not when I save the code to .py
c:\Python\Codes>python
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> [netifaces.ifaddresses(iface)[netifaces.AF_INET][0]['addr'] for iface in netifaces.interfaces() if netifaces.AF_INET in netifa
ces.ifaddresses(iface)]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'netifaces' is not defined
>>>
>>> import netifaces
>>> [netifaces.ifaddresses(iface)[netifaces.AF_INET][0]['addr'] for iface in netifaces.interfaces() if netifaces.AF_INET in netifa
ces.ifaddresses(iface)]
['192.168.1.10', '192.168.56.1', '127.0.0.1']
>>>
>>> ^Z
It's not working when I save the code into .py
c:\Python\Codes>more test.py
[netifaces.ifaddresses(iface)[netifaces.AF_INET][0]['addr'] for iface in netifaces.interfaces() if netifaces.AF_INET in netifaces.
ifaddresses(iface)]
c:\Python\Codes>test.py
Traceback (most recent call last):
File "c:\Python\Codes\test.py", line 1, in <module>
[netifaces.ifaddresses(iface)[netifaces.AF_INET][0]['addr'] for iface in netifaces.interfaces() if netifaces.AF_INET in netifa
ces.ifaddresses(iface)]
NameError: name 'netifaces' is not defined
c:\Python\Codes>
c:\Python\Codes>more test.py
import netifaces
[netifaces.ifaddresses(iface)[netifaces.AF_INET][0]['addr'] for iface in netifaces.interfaces() if netifaces.AF_INET in netifaces.
ifaddresses(iface)]
c:\Python\Codes>
c:\Python\Codes>test.py
c:\Python\Codes>