or a binary streaming problem with PHP

Source: Internet
Author: User
Tags unpack
Before a post: http://bbs.csdn.net/topics/391024843
Moderator gave the answer, but also can parse out, but found out the results and the actual results are completely different, such as the server returned to me is: ip:107.145.107.140, port:26773
But I resolved it into: ip:46.48.46.48, port:63271
This is far away, I use PHP to get nodes information, and then the nodes information to parse the output, by the way, the unresolved data sent to Pthon parsing again, and then on both sides of the comparison, found that the results are not the same

PHP (using Swoole):
 Set (' Worker_num ' + worker_num, ' daemonize ' = False, ' max_request ' = = max_request, ' Dispatch_    Mode ' = + 2, ' Debug_mode ' + 1); $serv->on (' Start ', function ($serv) {echo "DHT Server start...\n";    $nid = get_node_id ();            $msg = Array (' t ' = = entropy (2), ' y ' = = ' Q ', ' q ' = ' find_node ', ' a ' = = Array (    ' id ' = $nid, ' target ' + $nid)); $serv->sendto (gethostbyname (' router.bittorrent.com '), 6881, Encode ($msg));});    $serv->on (' Receive ', function ($serv, $FD, $from _id, $data) {echo "New Receive from IP:";    $msg = decode ($data);    $fdinfo = $serv->connection_info ($FD); echo $fdinfo [' remote_ip '].    "\ n"; if ($msg [' y '] = = ' R ') {if (array_key_exists (' nodes ', $msg [' r]))//$this->response_actions ($msg, Array (            $fdinfo [' remote_ip '], $fdinfo [' Remote_port ']);            $nodes = Decode_nodes ($msg [' R '] [' nodes ']); foreach ($nodes as $nODE) {echo "Nid:". $node->nid. ", IP:". $node->ip. ", Port:". $node->port.            "\ n";    } $serv->sendto (' 127.0.0.1 ', 6813, $data);        }}); function entropy ($length =20) {$s = ';        for ($i =0; $i < $length; $i + +) $s. = Chr (Mt_rand (0, 255));    return $s;    }function get_node_id () {return SHA1 (entropy ());    }function Get_neighbor ($target, $nid) {return substr ($target, 0, ten). substr ($nid, 0,-10);    }function encode ($msg) {return bencode::encode ($msg);    }function Decode ($msg) {return Bencode::d ecode ($msg);        }function Decode_nodes ($msg) {$n = array ();        $length = strlen ($msg);        Since each node is 26 bits, if the total length is not equal to a multiple of 26, it returns the IF (($length%)! = 0) return $n;        $i = 0;            while ($i < $length) {//$s = substr ($msg, $i, 26);            $d = Unpack (' A20nid/lip/sport ', $s);            Var_dump ($d); $d = Unpack (' A20nid/lip/spoRT ', $s);            Var_dump ($d);            $n [] = new Node ($d [' nid '], Long2ip ($d [' IP ']), $d [' Port '];            $nid = substr ($msg, $i, 20);            Var_dump ($nid);            $ip = substr ($msg, $i +20, 4);            Var_dump ($IP);            $ip = Long2ip (Unpack (' L ', $IP) [1]);            $port = substr ($msg, $i +24, 2);            Var_dump ($port);            $port = Unpack (' s ', $port) [1];            Var_dump ($port);            $n [] = new Node ($nid, $ip, $port);        $i + = 26;    } return $n; } $serv->start ();


Python:
#!/usr/bin/env python#encoding:utf-8import socketfrom hashlib import sha1from random import randintfrom struct import UNP Ackfrom Socket Import inet_ntoafrom Threading import Timer, Threadfrom time import sleepfrom collections Import Dequefrom Bencode import Bencode, Bdecodedef decode_nodes (nodes): n = [] length = Len (nodes) if (length%)! = 0:r Eturn N for i in range (0, length, up): Nid = nodes[i:i+20] ip = Inet_ntoa (nodes[i+20:i+24]) IP2 = NODES[I+20:I+24] Print IP2 port = Unpack ("! H ", nodes[i+24:i+26]) [0] port2 = nodes[i+24:i+26] Print port2 print" Decode_nodes:nid:%s, IP:%s, p ORT:%s\n "% (Nid, IP, Port) class Dhtserver (): Def __init__ (self): SELF.UFD = Socket.socket (socket.af_inet, sock Et. SOCK_DGRAM, Socket.  IPPROTO_UDP) Self.ufd.bind (("0.0.0.0", 6813)) def process_find_node_response (self, MSG, address): nodes =         Decode_nodes (msg["R" ["Nodes"]) for node in nodes:   (Nid, IP, port) = node print "Find_node:nid:%s, IP:%s, port:%s\n"% (Nid, IP, Port) def run (self): While True:try: (data, address) = Self.ufd.recvfrom (65536) msg = Bdecode (da TA) self.on_message (msg, address) except Exception:pass def on_message (self,                    MSG, address): Try:if msg["y"] = = "R": if Msg["R"].has_key ("Nodes"): Self.process_find_node_response (msg, address) except keyerror:passif __name__ = = "__main__": # Max_n Ode_qsize bigger, bandwith bigger, spped higher DHT = Dhtserver () dht.run ()


Reply to discussion (solution)

You use the $msg when you execute Decode_nodes ($msg)
echo Base64_encode ($msg);
Output and look.

This is not base64 encoding, but similar to:
Not encoded: {"T": "AA", "Y": "R", "R": {"id": "0123456789abcdefghij", "Nodes": "Def456 ..."}}
After encoding: D1:rd2:id20:0123456789abcdefghij5:nodes9:def456...e1:t2:aa1:y1:re
Such a format

And the Nodeid, the IP, and the port are among the nodes.

You use the $msg when you execute Decode_nodes ($msg)
echo Base64_encode ($msg);
Output and look.



Here's a DHT protocol description: http://blog.csdn.net/xxxxxx91116/article/details/7970815

I'm not doing this, I'm not interested in reading the protocol text

I gave you the decoding format is small end sequence, if your data is big endian, then check the pack function description, change

If you want me to check for you, please do as I say.

4 floor Moderator said the right, check the size of the problem of the end sequence.
Or what the actual binary data is with tcpdump.

Now has been able to correctly obtain the IP address, but the port is still no solution, but also is the use of big-endian, but PHP only these several formats, each tried, is not correct, depressed ...

What's the way? Let you post the data, and you won't.

Oh, no, no, no, it's like this:
For example, the server sent a piece of data, IP is: 188.19.238.146, the port is: 6881, then I intercept the port bit of 2 bytes of data:?
Then the decoding, the network byte order into the port number: unpack ("n", $port), but the conversion has become 57763, with unpack ("s", $port) into 23583, with unpack ("s", $port) into 41953

Why is it so hard for you to encode the data you received with Base64_encode?

Why is it so hard for you to encode the data you received with Base64_encode?


Sorry, this is the data:
zde6cmqyomlkmja6dacpq0zcdc6jp5an4ac4g4tlvpg1om5vzgvznde2oj4jyz4wvioixzae2mxw4twch8dddz6srdktj+ 7silgra0ylqqlqucmpix2e6mzcvq2zy90lczorzu5zytoywpbtkzh4pvnlmrz+ vo4exiqgyeuq3sv501vnwq5xcqsxfxftr47cyrvzhsf4dcdfwnmcgc2aq/ dhvz00wbxfm9qpqlsdaj4um4dxnvtz6blcggy42pw3zvonrorqvgpfb1j5g+ baxb2noumbbw7fqcyycnbojcpadatl59ekq4hpahqd1gw057xisirlgep9f9vzvdr60s6c3cbncx/ovotfejyy40k3sdswz1ltimgvqrb7t7/ Vto1rgxkzftpuvaybpcjawupbxcilozh8a8h/qzkyirim0v8lycjgffdeizr7bq+apmxhvl1scc6m3ymh17kia8lk3l06cqn65evx3/cuwj4uw +fdhqsjvckrwlpdqyo8k8mjkzhdvaahcbudxw9eslvaxxuygufhyq2gv1bohsygmpjsaozkghl0kq9lciqvwuhr/ewsm/x/ 90cexsts45jet3hqwuz2kcjvzte6ddi6e8cxonkxonjl

Python has the

    n = []    length = len (nodes)    if (length%)! = 0:        return n
And the data you give (decoded) length is 474
Modulo 26 is 6
Please make sure the data you gave is correct.

Python has the

    n = []    length = len (nodes)    if (length%)! = 0:        return n
And the data you give (decoded) length is 474
Modulo 26 is 6
Please make sure the data you gave is correct.



Oh, I'm sorry, that's right, just give the original data obtained, and then the 26 that is through the Bencode decoded after the nodes data, sorry, forgot to put this data also out ...

This is the original data, which contains all the obtained, for example: y = r, etc.
zde6cmqyomlkmja6o+bji1uaqd0dtxqvyyoa6qxswgq1om5vzgvznde2oj/ sypvgoewnka31unep7simr5o0tuvci3zxp9li9uagry0odfvscsnuykzhmjro68kldlc/0sj1rqbfjsgn9vjxke7ipkeane7rwot2vz/8i+ 41pitghxjvpesigtto7b2usbfqyb+qp/wj7ju8hmydclu8rkiznm7tvzsxt+rih5a//cpuntyexh1yvtxeohk0zu29llg36sgfkd// toin7ijhpgnlvhneku1io1b2zcxgphrhp/9m6kfukoe8aew+e0ss7ug7uhzlzey+gue//0zop+ 4o4txp5b4trjltsdtqdmxmrj4a4t5ojqm7nuwy8rsq0ca2ri235aiypbmggbrhpk6nazs25zjxfkrqjrzejbfkahg8gyaague+ to0dozblmpeuqtamtksnt+qcgdwzhoaa4t7pzbzs/9sbpdganmeq8dhehtgbueasw9vgps9ltmz/1jul2aa0wrdx0d4e2afr4czd2+a+z2w2bp /um6xyadtbephr3h7yavhglmpb4d2owbnmjwrvv7qjzqoem7j+lo0o36b9drrhzte6ddg6lzgymod7p/sxonkxonjl


This is the nodes data decoded by Bencode, that is, in this data is divided into 26 bytes per copy, from 26 bytes to remove 20 bytes of nid,4 bytes of ip,2 byte port:
p9li9uagry0odfvscsnuykzhmjro68kldlc/0sj1rqbfjsgn9vjxke7ipkeane7rwot2vz/sypvgoewnka31unep7simr5o0tuvci3zxp/ wj7ju8hmydclu8rkiznm7tvzsxt+rih5a//cpuntyexh1yvtxeohk0zu29llg36sgfkd/8i+41pitghxjvpesigtto7b2usbfqyb+qp/ 9m6kfukoe8aew+e0ss7ug7uhzlzey+gue//0zop+4o4txp5b4trjltsdtqdmxmrj4a4t// toin7ijhpgnlvhneku1io1b2zcxgphrhpk6nazs25zjxfkrqjrzejbfkahg8gyaague+to0dozblmpeuqtamtksnt+ qcgdwzhoaa4t5ojqm7nuwy8rsq0ca2ri235aiypbmggbrhps9ltmz/1jul2aa0wrdx0d4e2afr4czd2+a+z2w2bp/ Um6xyadtbephr3h7yavhglmpb4d7pzbzs/9sbpdganmeq8dhehtgbueasw9vgpajae2ylzg+/uqpncgqzup6wjq7fpv0ngue=

 $s = ' p9li9uagry0odfvscsnuykzhmjro68kldlc/0sj1rqbfjsgn9vjxke7ipkeane7rwot2vz/ sypvgoewnka31unep7simr5o0tuvci3zxp/wj7ju8hmydclu8rkiznm7tvzsxt+rih5a//cpuntyexh1yvtxeohk0zu29llg36sgfkd/8i+ 41pitghxjvpesigtto7b2usbfqyb+qp/9m6kfukoe8aew+e0ss7ug7uhzlzey+gue//0zop+4o4txp5b4trjltsdtqdmxmrj4a4t// toin7ijhpgnlvhneku1io1b2zcxgphrhpk6nazs25zjxfkrqjrzejbfkahg8gyaague+to0dozblmpeuqtamtksnt+ qcgdwzhoaa4t5ojqm7nuwy8rsq0ca2ri235aiypbmggbrhps9ltmz/1jul2aa0wrdx0d4e2afr4czd2+a+z2w2bp/ Um6xyadtbephr3h7yavhglmpb4d7pzbzs/9sbpdganmeq8dhehtgbueasw9vgpajae2ylzg+/uqpncgqzup6wjq7fpv0ngue= '; $s = base64_  Decode ($s); foreach (Str_split ($s) as $s) {$r = unpack (' a20n/nip/np ', $s);  $r [' ip '] = long2ip ($r [' IP ']); Print_r ($r);} 
Array ([n] = =? Òèõf E? (ÕRQ) îè¦g?4 [IP] = 78.235.194.139 [P] = 30295) Array ([n] = =? Òèõf E? (ÕRQ) îè¦g?4 [IP] = 78.235.194.139 [P] = 30295) Array ([n] = =? Òèõf E? (ÕRQ) îè¦g?4 [IP] = 78.235.194.139 [P] + 30295) Array ([n] = = Ü#î5
 177.183.234.200 [P] = 8080) Array ([n] = = Ü#î5
 177.183.234.200 [P] = 8080) Array ([n] = = Ü#î5
 177.183.234.200 [P] = 8080) Array ([n] = = Ÿlè§î (á
 
  
    101.204.70.62 [P] = 6881)  Array ([n] = = ÿlè§î (á
   
     101.204.70.62 [P] = 6881) array ([n] = Ÿlè§î (á
    
      101.204.70.62 [P] = 6881) Array ([n] = >N?; 6å?ñª?&¶d? Ä[IP] = 60.25.134.128 [P] = 6881) Array ([n] = >N?; 6å?ñª?&¶d? Ä[IP] = 60.25.134.128 [P] = 6881) Array ([n] = >N?; 6å?ñª?&¶d? Ä[IP] = 60.25.134.128 [P] = 6881) Array ([n] = >ïe¶lÿô?¥ø4áññ? Ø[IP] = 81.224.44.195 [P] = 56288) Array ([n] = >ïe¶lÿô?¥ø4áññ? Ø[IP] = 81.224.44.195 [P] = 56288) Array ([n] = >ïe¶lÿô?¥ø4áññ?    Ø[IP] = 81.224.44.195 [P] = 56288) Array ([n] = =¨àf%do¿º£í3¸??? [IP] = 223.166.253.13 [P] = 6881) 
     
     
  
 
There should be no problem.

$s = ' p9li9uagry0odfvscsnuykzhmjro68kldlc/0sj1rqbfjsgn9vjxke7ipkeane7rwot2vz/sypvgoewnka31unep7simr5o0tuvci3zxp/ wj7ju8hmydclu8rkiznm7tvzsxt+rih5a//cpuntyexh1yvtxeohk0zu29llg36sgfkd/8i+41pitghxjvpesigtto7b2usbfqyb+qp/ 9m6kfukoe8aew+e0ss7ug7uhzlzey+gue//0zop+4o4txp5b4trjltsdtqdmxmrj4a4t// toin7ijhpgnlvhneku1io1b2zcxgphrhpk6nazs25zjxfkrqjrzejbfkahg8gyaague+to0dozblmpeuqtamtksnt+ qcgdwzhoaa4t5ojqm7nuwy8rsq0ca2ri235aiypbmggbrhps9ltmz/1jul2aa0wrdx0d4e2afr4czd2+a+z2w2bp/ Um6xyadtbephr3h7yavhglmpb4d7pzbzs/9sbpdganmeq8dhehtgbueasw9vgpajae2ylzg+/uqpncgqzup6wjq7fpv0ngue= '; $s = base64_ Decode ($s); foreach (Str_split ($s) as $s) {  $r = unpack (' a20n/nip/np ', $s);  $r [' ip '] = long2ip ($r [' IP ']);  Print_r ($r);}
Array ([n] = =? Òèõf E? (ÕRQ) îè¦g?4 [IP] = 78.235.194.139 [P] = 30295) Array ([n] = =? Òèõf E? (ÕRQ) îè¦g?4 [IP] = 78.235.194.139 [P] = 30295) Array ([n] = =? Òèõf E? (ÕRQ) îè¦g?4 [IP] = 78.235.194.139 [P] + 30295) Array ([n] = = Ü#î5
 177.183.234.200 [P] = 8080) Array ([n] = = Ü#î5
 177.183.234.200 [P] = 8080) Array ([n] = = Ü#î5
 177.183.234.200 [P] = 8080) Array ([n] = = Ÿlè§î (á
 
  
    101.204.70.62 [P] = 6881)  Array ([n] = = ÿlè§î (á
   
     101.204.70.62 [P] = 6881) array ([n] = Ÿlè§î (á
    
      101.204.70.62 [P] = 6881) Array ([n] = >N?; 6å?ñª?&¶d? Ä[IP] = 60.25.134.128 [P] = 6881) Array ([n] = >N?; 6å?ñª?&¶d? Ä[IP] = 60.25.134.128 [P] = 6881) Array ([n] = >N?; 6å?ñª?&¶d? Ä[IP] = 60.25.134.128 [P] = 6881) Array ([n] = >ïe¶lÿô?¥ø4áññ? Ø[IP] = 81.224.44.195 [P] = 56288) Array ([n] = >ïe¶lÿô?¥ø4áññ? Ø[IP] = 81.224.44.195 [P] = 56288) Array ([n] = >ïe¶lÿô?¥ø4áññ?    Ø[IP] = 81.224.44.195 [P] = 56288) Array ([n] = =¨àf%do¿º£í3¸??? [IP] = 223.166.253.13 [P] = 6881) 
     
     
  
 
There should be no problem.



Thank you very much, it seems that I first intercepted the interception is wrong, so the results will be wrong, really thank you!
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.