Regarding the pack in PHP, how can the HET hexadecimal stream be decoded? I tried to use PHP for a dht Crawler. because data transmission uses bencode, this is okay and can be correctly decoded. However, if find_node data is sent, there is a nodes in the obtained data, which is a binary stream encoded using the struct structure. according to the dht protocol, it is: 20-byte node id + 4-byte ip address + 2-byte Port. I have read the encoding and decoding method in python, but it cannot be converted to php. in python, the conversion is as follows:
Def decodeNodes (nodes): "converts the received nodes into an example table. data format: [(node ID, ip, port), (node ID, ip, port), (node ID, ip, port)...] "n = [] nrnodes = len (nodes)/26 nodes = unpack ("! "+" 20sIH "* nrnodes, nodes) for I in xrange (nrnodes): nid, ip, port = nodes [I * 3], numToDottedQuad (nodes [I * 3 + 1]), nodes [I * 3 + 2] print nid n. append (nid, ip, port) return ndef encodeNodes (nodes): "encoding" nodes is opposite to decodeNodes "n = [] for node in nodes: n. extend ([node. nid, dottedQuadToNum (node. ip), node. port]) return pack ("! "+" 20sIH "* len (nodes), * n)
How can this conversion be achieved in PHP?
Reply to discussion (solution)
20-byte node id: a20 or A20. if the space is insufficient, use the latter.
4-byte ip: L the ip address is converted into an unsigned long integer using ip2long.
2-byte Port: S
Package
$ S = pack ('a20ls', $ nodeid, ip2logn ($ ip), 456 );
Unpack
$ D = unpack ('a20nodeid/Lip/Sport ', $ s );
$ D ['IP'] = logn2ip ($ d ['IP']);
Print_r ($ d); // It is clear.
20-byte node id: a20 or A20. if the space is insufficient, use the latter.
4-byte ip: L the ip address is converted into an unsigned long integer using ip2long.
2-byte Port: S
Package
$ S = pack ('a20ls', $ nodeid, ip2logn ($ ip), 456 );
Unpack
$ D = unpack ('a20nodeid/Lip/Sport ', $ s );
$ D ['IP'] = logn2ip ($ d ['IP']);
Print_r ($ d); // It is clear.
Thank you very much for solving this problem.