[TOC]

The foreword 0.

There are two versions of IP addresses: IPv4 and IPv6. The most common version we see is IPv4, such as 192.168.1.1/24. Of course,IPv4 address pool resources are scarce, and IPv6 has been quietly deployed in large numbers.

When we design the network architecture, we must plan the device interconnection address, loopback address, and service address. How to plan? What would you do if I gave you A class A address? Is the most important thing to calculate? Is it not accurate? Mental arithmetic is ok, not afraid that you do not have this ability, haha!

Let’s do it for you in Python!

1. Ipaddress module

1.1 IP Host address

Description: No mask

How do you know if it’s an ipv4 address or an ipv6 address? Use the ipaddress.ip_address() function to find out:

>>> ipaddress.ip_address('192.168.1.1')
IPv4Address('192.168.1.1')
>>> ipaddress.ip_address('192.168.1.1').version
4

>>> ipaddress.ip_address('fe80::1')
IPv6Address('fe80::1')
>>> ipaddress.ip_address('fe80::1').version
6
Copy the code

If the mask is used, an error will be reported:

>>> ipaddress.ip_address('192.168.1.1/32')
Traceback (most recent call last):
  File "<stdin>", line 1.in <module>
  File "/ usr/lib/python3.5 ipaddress. Py." ", line 54.in ip_address
    address)
ValueError: '192.168.1.1/32' does not appear to be an IPv4 or IPv6 address
Copy the code

1.2 Defining a Network

Note: Indicates a network segment

An IP address, usually consisting of a network number plus a network prefix, such as 192.168.1.0/24, can be represented by the ipaddress.ip_network function. By default, Python only recognizes a network number, and an IP host will report an error. Of course you can avoid this by saying strict=False.

>>> ipaddress.ip_network('192.168.1.0/24')
IPv4Network('192.168.1.0/24')

# By default, an error will be reported if the host bit is entered
>>> ipaddress.ip_network('192.168.1.1/24')
Traceback (most recent call last):
  File "<stdin>", line 1.in <module>
  File "/ usr/lib/python3.5 ipaddress. Py." ", line 74.in ip_network
    return IPv4Network(address, strict)
  File "/ usr/lib/python3.5 ipaddress. Py." ", line 1536.in __init__
    raise ValueError('%s has host bits set' % self)
ValueError: 192.1681.1./24 has host bits set  The host IP address is displayed

# Change bit non-strict mode, default is strict=True
>>> ipaddress.ip_network('192.168.1.1/24' , strict=False)
IPv4Network('192.168.1.0/24')   # Return the network number
Copy the code

1.3 Host Port

Description: Indicates the interface address(IP/mask). Generally, the IP address is configured on the interface of the router, switch, and firewall in the format of 192.168.1.1/24. If the ipaddress.ip_address() and ipaddress.ip_network functions are used, it is not easy to express. This can be represented by the ipaddress.ip_interface() function class.

>>> ipaddress.ip_interface('192.168.1.1/24')
IPv4Interface('192.168.1.1/24')
Copy the code

1.4 check the address/network/interface object

1.4.1 Checking IP Version (V4 or V6) :

>>> ipaddress.ip_address('192.168.1.1').version
4
>>> ipaddress.ip_address('fe80::1').version
6
Copy the code

1.4.2 Obtaining the network segment from the IP address of the Interface

>>> ipaddress.ip_interface('192.168.1.1/24').network
IPv4Network('192.168.1.0/24')

>>> ipaddress.ip_interface('fe80::/64').network
IPv6Network('fe80::/64')
Copy the code

1.4.3 Compute how Many IP Addresses Exist in the Network Segment

>>> ipaddress.ip_network('192.168.1.0/24').num_addresses
256

>>> ipaddress.ip_network('fe80::/64').num_addresses
18446744073709551616
Copy the code

1.4.4 Compute the Number of Available IP addresses in the Network Segment

>>> net = ipaddress.ip_network('192.168.1.0/24') > > >for x in net.hosts():
...     print(x) ... 192.168.1.1 192.168.1.2 instead... 192.168.1.100 192.168.1.101... 192.168.1.254 > > > [xfor x in net.hosts()][0]     # Get the first available IP
IPv4Address('192.168.1.1')
>>> [x for x in net.hosts()][-1]    Get the last available IP address
IPv4Address('192.168.1.254')
Copy the code

1.4.5 Obtaining the Mask and Wildmask

>>> ipaddress.ip_network('192.168.1.1/24' , strict=False).netmask
IPv4Address('255.255.255.0')    # Get the mask

>>> ipaddress.ip_network('192.168.1.1/24' , strict=False).hostmask
IPv4Address('0.0.0.255')    # Get the inverse mask
Copy the code

1.6 Obtaining the Network Number and Broadcast Address

>>> ipaddress.ip_network('192.168.1.1/24' , strict=False).network_address
IPv4Address('192.168.1.0')      # Get the network number

>>> ipaddress.ip_network('192.168.1.1/24' , strict=False).broadcast_address
IPv4Address('192.168.1.255')    # Get the broadcast address
Copy the code

1.7 Exception Handling

If the IP address format does not meet the requirements, what to do?

# Error display with "ValueError"
>>> ipaddress.ip_network('192.168.1.1/24')
Traceback (most recent call last):
  File "<stdin>", line 1.in <module>
  File "/ usr/lib/python3.5 ipaddress. Py." ", line 74.in ip_network
    return IPv4Network(address, strict)
  File "/ usr/lib/python3.5 ipaddress. Py." ", line 1536.in __init__
    raise ValueError('%s has host bits set' % self)
ValueError: 192.1681.1./24 has host bits set

# Handle exceptions with a try-except statement
>>> import ipaddress
>>> def cal_ip(net):
.    try:
.        net = ipaddress.ip_network(net)
.        print(net)
.    except ValueError:
.        print('You entered the wrong format, please check! ')
.
>>> cal_ip(net = '192.168.1.1/24') Your input format is wrong, please check!Copy the code

2. Calculation of IP subnet code demonstration

2.1 Complete Code

#! /usr/bin/env python3
#-*- coding:UTF-8 -*-
Welcome to wechat official account: Drip Technology

import ipaddress

def cal_ip(ip_net):
    try:
        net = ipaddress.ip_network(ip_net, strict=False)
        print('IP version number: ' + str(net.version))
        print('Private address:' + str(net.is_private))
        print(Total number of IP addresses: + str(net.num_addresses))
        print(Total number of available IP addresses: + str(len([x for x in net.hosts()])))
        print('Network number:' + str(net.network_address))
        print('Start available IP address:' + str([x for x in net.hosts()][0]))
        print('Last available IP address:' + str([x for x in net.hosts()][- 1]))
        print('Available IP address range:' + str([x for x in net.hosts()][0]) + '~' + str([x for x in net.hosts()][- 1]))
        print('Mask address:' + str(net.netmask))
        print(Inverse mask address: ' + str(net.hostmask))
        print('Broadcast address:' + str(net.broadcast_address))
    except ValueError:
        print('You entered the wrong format, please check! ')

if __name__ == '__main__':
    ip_net = '192.168.1.1/24'
    cal_ip(ip_net)
Copy the code

2.2 Operation Result

IP version:4Private address:TrueTotal IP addresses:256Total number of available IP addresses:254The network number:192.1681.. 0Start AVAILABLE IP address:192.1681.1.Last available IP address:192.1681.254.Available IP address range:192.1681.1. ~ 192.1681.254.Mask Address:255.255255.. 0Inverse mask address:0.0. 0255.Broadcast Address:192.1681.255.
Copy the code

3. The crushed SuiYu

How, after learning is not very excited, do not need to use other tools to calculate it, use Python to help you do it.

3.1 Official Reference Documents

Docs.python.org/3.8/howto/i…


If you like my article, welcome to follow my public number: drip technology, scan code attention, irregularly share