IP

Python

Python uses the package socket described at socket — Low-level networking interface

IP types

There is the type ipaddress.ip_address with subclasses IPv4Address and IPv6Address. Example construtors are


      ipaddress.IPAddress('192.168.0.1')
      ipaddress.IPAddress(3232235521)
      ipaddress.IPAddress(b'\xC0\xA8\x00\x01')
  
all of which are the same IPv4 address.

The method version will return 4 or 6 depending on the type, and there are methods such as is_global

Get one DNS address

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[1])
except:
    print('No address found')
    exit(2)
    
print(addr)
exit(0)

Get all DNS addresses

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[1], 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[4][0]
    ips.add(addr)

print(ips)
exit(0)

    

Get all addresses for an interface

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. The method socket.if_nameindex() returns all iface names though, getting partially there.


Copyright © Jan Newmarch, jan@newmarch.name
Creative Commons License
" Network Programming using Java, Go, Python, Rust, JavaScript and Julia" by Jan Newmarch is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License .
Based on a work at https://jan.newmarch.name/NetworkProgramming/ .

If you like this book, please contribute using PayPal