从本地ip获取远程ip

2024-04-25 14:34:40 发布

您现在位置:Python中文网/ 问答频道 /正文

给定本地IP地址(IP):u'1.1.1.1/32'#unicode格式

如何获取远端ip?(将是1.1.1.2)

逻辑:

如果本地ip为偶数,则远程ip将为本地ip+1

否则,本地ip-1

我试着这样做:

ip_temp = int(ip.replace('/32','').split('.')[-1])
if ip_temp % 2 == 0:
    remote = ip + 1
else:
    remote = ip - 1
remote_ip = <replace last octet with remote>

我查看了ipaddress模块,但找不到任何有用的东西


Tags: ipif远程remote格式unicode逻辑temp
1条回答
网友
1楼 · 发布于 2024-04-25 14:34:40

大多数Python套接字实用程序要求远程IP是一个具有字符串和端口号(整数)的元组。例如:

import socket
address = ('127.0.0.1', 10000)
sock.connect(address)

对于您的案例,您拥有所需的大部分逻辑。但是,您需要确定如何处理X.X.X.0和X.X.X.255的情况。
执行所需操作的完整代码是:

ip = '1.1.1.1/32'

# Note Drop the cidr notation as it is not necessary for addressing in python
ip_temp = ip.split('/')[0]
ip_temp = ip_temp.split('.')
# Note this does not handle the edge conditions and only modifies the last octet
if int(ip_temp[-1]) % 2 == 0:
    remote = int(ip_temp[-1]) + 1
else:
    remote = int(ip_temp[-1]) -1
remote_ip = ".".join(ip_temp[:3]) + "." + str(remote)

相关问题 更多 >