python - 当在Python中的步骤中给出IP地址时增加IP地址

标签 python ip-address

当我们有 4 个八位字节 格式的 start_ip 并且步骤也采用 4 个八位字节格式时,如何在 python 中增加 IP 地址。

假设我从 IP 地址 225.1.1.1 开始,步骤为 0.0.0.1 当我说 next_ip = start_ip + step 时,它实际上应该评估扩展产生的结果。 我知道 ipaddr 模块只需添加一个即可完成此操作,但当该步骤也以 ipv4 格式给出时,这似乎不起作用。

执行此操作的任何已知步骤:

import ipaddr 
a = ipaddr.ipaddress('225.1.1.1')
b = a +1

这实际上返回了期望的结果。但是当像这样增加时:

b = a + 0.0.0.1 it does not seem to work.

有任何已知的解决方案吗?

最佳答案

未精炼,但我猜可以用,这是 python 片段

def increment_ip_addr(ip_addr):
    ip_arr = ip_addr.split('.')

    def increment_by_1(digit):
        return str(int(digit) + 1)

    if int(ip_arr[3]) > 254:
        ip_arr[3] = "1"
        if int(ip_arr[2]) > 254:
            ip_arr[2] = "1"
            if int(ip_arr[1]) > 254:
                ip_arr[1] = "1"
                if int(ip_arr[0]) > 254:
                    ip_arr[0] = "1"
                else:
                    ip_arr[0] = increment_by_1(ip_arr[0])
            else:
                ip_arr[1] = increment_by_1(ip_arr[1])
        else:
            ip_arr[2] = increment_by_1(ip_arr[2])
    else:
        ip_arr[3] = increment_by_1(ip_arr[3])
    print(f"for ip address: {ip_addr} The incremented ip is: {'.'.join(ip_arr)}")

[increment_ip_addr(ip_addr) for ip_addr in ['1.1.1.1', "1.1.1.255", "1.255.1.255", "255.255.255.255"]]

对应的控制台输出:

for ip address: 1.1.1.1 The incremented ip is: 1.1.1.2
for ip address: 1.1.1.255 The incremented ip is: 1.1.2.1      
for ip address: 1.255.1.255 The incremented ip is: 1.255.2.1  
for ip address: 255.255.255.255 The incremented ip is: 1.1.1.1

如果有优化版本请告诉我

关于python - 当在Python中的步骤中给出IP地址时增加IP地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59801524/

相关文章:

Python + Scrapy + JSON + XPath : How to scrape JSON data with Scrapy

python - 创建文本文档 (Python)

python - 在给定 Python 中的 IPv4 地址列表的情况下获取最小网络

c# - 从 IPHostEntry 获取有效 IP

Python 类似于 Groovy 中的列表切片

python - 使用 odo 将 Pandas Dataframe 复制到 Postgres

python - 了解 Python WSGI 应用程序中的全局对象持久性

linux - 在 debian linux 上更改和同步主机名/IP 地址更改

perl - 记录 IP 地址的唯一性,而不存储 IP 地址本身以保护隐私

c# - 如何从 System.Net.EndPoint 获取主机地址和端口?