2015-12-01 43 views
0

獲得遠程IP給本地端的IP地址(IP):u'1.1.1.1/32' #unicode格式從本地IP

如何獲得遠程端的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> 

我看着ip地址模塊,但無法找到任何有用

回答

0

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