【问题标题】:getting remote ip from local ip从本地ip获取远程ip
【发布时间】:2015-12-01 01:08:42
【问题描述】:

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

【问题讨论】:

    标签: python ip-address


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2020-11-29
      • 1970-01-01
      • 1970-01-01
      • 2011-11-12
      • 2012-02-07
      • 2012-03-01
      • 2012-03-22
      • 2018-10-11
      • 2011-06-13
      相关资源
      最近更新 更多