从本地ip获取远程ip

getting remote ip from local ip

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

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

逻辑:

如果本机ip为偶数,则远端ip为本机ip + 1

else,本地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 模块,但找不到任何有用的东西

大多数 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)