希望提高我的代码效率,因为当我的方法有效时,我觉得它可以改进
目前这是我的代码:
if ouroraddrlen == (4,):
ouropip = struct.unpack(">bbbb", payload[6:10]) # Need to change this to accept ipv6 as well
print "Our I.P : ", ouropip
notheirip = struct.unpack(">b", payload[10])
print "No. of their I.P's : ", notheirip
theiroripv = struct.unpack(">b", payload[11])
print "Their I.P version:: ", theiroripv
theiroraddrlen = struct.unpack(">b", payload[12])
print "Length of their Ip : ", theiroraddrlen
theirfirstip = struct.unpack(">bbbb", payload[13:17])
print "First Ip : ", theirfirstip
theirsecondip = struct.unpack(">bbbb", payload[18:22])
print "Second Ip : ", theirsecondip
输出是:
Time : (1401734263,)
Our onion address :
Ip version : (4,)
Ip length : (4,)
Our I.P : ( )
No. of their I.P's : (2,)
Their I.P version:: (4,)
Length of their Ip : (4,)
First Ip : ( )
Second Ip : ( )
我删除了真正的ip,但它们只是ipv4地址
然而我想知道的是,是否可以在此部分代码之后包含if语句:
notheirip = struct.unpack(">b", payload[10])
print "No. of their I.P's : ", notheirip
如果notheirip大于零并且取决于:
的长度 theiroraddrlen = struct.unpack(">b", payload[12])
print "Length of their Ip : ", theiroraddrlen
将是4或16然后它将设置下一部分的有效载荷值
例如,如果notheirip =(2,)和theiroraddrlen =(4,)那么我希望它打印出来
hisip = struct.unpack(“> b<<所需b的数量为4或16然后是范围,这将始终从13开始,并在未来升至4或16循环直到显示所有的ip
不确定这是否清楚,但希望是:)
由于
答案 0 :(得分:1)
>>> from collections import namedtuple
>>> Record = namedtuple("Record","IP NoIP IPV LenIP FirstIP SecondIP")
>>> Record._asdict(Record._make(struct.unpack(">LbbbLL",payload[6:])))
{'FirstIP': 1145324612, 'NoIP': 17, 'SecondIP': 1431655765, 'IP': 3140690449L,
IPV': 34, 'LenIP': 51}
>>>
我认为可行(你可能想要不同的4字节类型而不是L)(请记住我完全弥补了有效载荷,所以我希望有一个真实的不同结果)
如果你想为ips获得4位数的元组,只需解压缩新值
new_record["IP"] = stuct.unpack("bbbb",new_record["IP"])