首先,我想知道这个python句子的作用:
var a = {
count: [{label:'a', value: 'a'}],
next: [{label:'b', value: 'b'}],
previous: [{label:'c', value: 'c'}]
}
function get_item() {
var x = "a"
for (let item in a){
let resultItem = a[item].find((obj)=>{ return obj.value === x });
if(resultItem) return item //you can also return 'resultItem';
}
}
console.log(get_item())
其次,我必须使用python发出ICMP请求消息,问题是我已经得到了老师给我帮助的一些代码:
struct.unpack("!%sH" % (len(data) / 2), data))
事情是理论上所有这些代码都是正确的,所以我只应该做" create_packet"功能,我在这里包括:
def step4(code, server, port):
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname('icmp'))
CHARMAP = nonprintable_to_dots()
packet = create_packet(int(code))
s.sendto(packet, (server, port))
while True:
msg = s.recv(1600)
if not msg:
break
ihl = (ord(msg[0]) & 0x0F) * 4
icmp = msg[ihl:]
hexdump(icmp, True)
if cksum(icmp[:]) != 0:
print("wrong ckecksum!!")
def nonprintable_to_dots():
return str.join('', [c if c in printable[:-5] else '.' for c in map(chr, range(256))])
def hexdump(frame, with_time=False):
def to_chr(bytes):
retval = bytes.translate(CHARMAP)
return retval[:8] + ' ' + retval[8:]
def to_hex(bytes):
retval = str.join(' ', ["%02X" % ord(x) for x in bytes])
return retval[:23] + ' ' + retval[23:]
if with_time:
print('--' + time.strftime("%H:%M:%s"))
for i in range(0, len(frame), 16):
line = frame[i:i + 16]
print('%04X %-49s |%-17s|' % (i, to_hex(line), to_chr(line)))
print
def cksum(data):
def sum16(data):
"sum all the the 16-bit words in data"
if len(data) % 2:
data += '\0'
return sum(struct.unpack("!%sH" % (len(data) / 2), data))
retval = sum16(data) # sum
retval = sum16(struct.pack('!L', retval)) # one's complement sum
retval = (retval & 0xFFFF) ^ 0xFFFF # one's complement
return retval
每当我执行脚本时,我总是会收到此错误:
def create_packet(code):
ICMP_REQUEST = 8
checksum = 0
identifier = 7
sequence_number = 7
message_header = struct.pack("!BBHHH", ICMP_REQUEST, 0, checksum, identifier, sequence_number)
message_payload = struct.pack("!I", code)
checksum = cksum(message_header + message_payload)
message_header = struct.pack("!BBHHH", ICMP_REQUEST, 0, checksum, identifier, sequence_number)
return message_header + message_payload
嗯,这就是问题:)
对不起我的英语,我还在学习,感谢解决方案btw
答案 0 :(得分:1)
作为第一个问题的答案,这一行
struct.unpack("!%sH" % (len(data) / 2), data) # in Python 2
struct.unpack("!%sH" % (len(data) // 2), data) # in Python 3
说,取data
中的 n 字节(例如: 4字节)并将它们解释为 n / 2 unsigned短整数(示例: 2个整数),每个2个字节。开头的!
大约是字节顺序,意味着大端。 %s
会根据len(data) / 2
的值转换为一个或多个数字,因此在示例中,它与执行
struct.unpack("!2H", data)
您的bad char in struct format
例外是因为您提供的代码使用/
除法运算符。这在Python 2中是有效的。但在Python 3中它必须是//
。这是因为/
表示Python 2中的整数除法,但是Python 3中的浮点除法。所以在Python 3中,
"!%sH" % (len(data) / 2)
出现
struct.unpack("!2.0H", data)
解释了您的bad char
错误。