website/content/blog/ipaddressesinpython.md

44 lines
1.7 KiB
Markdown
Raw Normal View History

2020-09-07 20:23:39 -04:00
---
title: "How to get list of IP Addresses in Python"
date: 2020-09-07T20:03:24-04:00
draft: false
2022-01-02 14:24:29 -05:00
tags: ["Python", "Networking"]
2023-01-05 14:04:45 -05:00
medium_enabled: true
2020-09-07 20:23:39 -04:00
---
[Elemag](https://stackoverflow.com/users/2436840/elemag) on gave a quick solution on StackOverflow on [how to determine IP addresses with multiple NICS](https://stackoverflow.com/questions/270745/how-do-i-determine-all-of-my-ip-addresses-when-i-have-multiple-nics).
His one-line solution:
```python
import netifaces
ip_addresses = [netifaces.ifaddresses(iface)[netifaces.AF_INET][0]['addr'] for iface in netifaces.interfaces() if netifaces.AF_INET in netifaces.ifaddresses(iface)]
```
Expanded out to see what is happening
```python
import netifaces
interface_list = netifaces.interfaces()
# Get addresses, netmask, etc. information
address_entries = (netifaces.ifaddresses(iface) for iface in interface_list)
# Only pay attention to ipv4 address types
ipv4_address_entries = (address[netifaces.AF_INET] for address in address_entries if netifaces.AF_INET in address)
# Since multiple addresses can be associated, only look at the first ip address
ipv4_addresses = [address[0]['addr'] for address in ipv4_address_entries]
```
We can easily adjust this to ask for IPv6 addresses by using `netifaces.AF_INET6` instead.
```python
import netifaces
interface_list = netifaces.interfaces()
# Get addresses, netmask, etc. information
address_entries = (netifaces.ifaddresses(iface) for iface in interface_list)
# Only pay attention to ipv6 address types
ipv6_address_entries = (address[netifaces.AF_INET6] for address in address_entries if netifaces.AF_INET6 in address)
# Since multiple addresses can be associated, only look at the first ip address
ipv6_addresses = [address[0]['addr'] for address in ipv6_address_entries]
```