Python uses the package
socket described at
socket — Low-level networking interface
There is the type
Example construtors are
all of which are the same IPv4 address.
ipaddress.IPAddress('192.168.0.1') ipaddress.IPAddress(3232235521) ipaddress.IPAddress(b'\xC0\xA8\x00\x01')
version will return 4 or 6 depending on the type,
and there are methods such as
The following program gets a single IPv4 only, not IPv6 IP.py illustrates these:
import socket import sys if len(sys.argv) < 2: print('Usage: comm hostname') exit(1) try: # only gets IPv4 address addr = socket.gethostbyname(sys.argv) except: print('No address found') exit(2) print(addr) exit(0)
The following program gets all addresses IPs.py illustrates these:
import socket import sys if len(sys.argv) < 2: print('Usage: comm hostname') exit(1) try: allAddr = socket.getaddrinfo(sys.argv, None) except: print('No address found') exit(2) # format is array of (family, type, proto, canonname, sockaddr) # IPv4 sockaddr is (address, port) # IPv6 sockaddr is (address, port, flow info, scope id) ips = set() for tuple in allAddr: addr = tuple ips.add(addr) print(ips) exit(0)
There doesn't seem to be a generic solution but many O/S specific ones.
See e.g. https://stackoverflow.com/questions/24196932/how-can-i-get-the-ip-address-from-nic-in-python.
socket.if_nameindex() returns all iface names though, getting
Copyright © Jan Newmarch, firstname.lastname@example.org
Based on a work at https://jan.newmarch.name/NetworkProgramming/ .