PHP binary stream-php Tutorial

Source: Internet
Author: User
Or a post about the PHP binary stream before: http://bbs.csdn.net/topics/391024843
The moderator gave an answer and was able to parse it, but found that the result was completely different from the actual result. for example, the server returned to me: ip: 107.145.107.140, port: 26773.
But I resolved it into: ip: 46.48.46.48, port: 63271
This is far worse. I used PHP to get the nodes information, and then parsed and output the nodes information myself. By the way, I sent the unparsed data to pthon for resolution, then compare the two sides and find that the results are different.

PHP (swoole used ):
 Set (array ('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 .bittor0000.com '), 6881, encod E ($ 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 ($ no Des as $ node) {echo "nid :". $ node-> nid. ", ip :". $ node-> ip. ", port :". $ node-> port. "\ n" ;}$ serv-> sendto ('2017. 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, 10 ). substr ($ nid, 0,-10);} functio N encode ($ msg) {return Bencode: encode ($ msg);} function decode ($ msg) {return Bencode: decode ($ msg );} function decode_nodes ($ msg) {$ n = array (); $ length = strlen ($ msg); // since each node has 26 bits, if the total length is not equal to a multiple of 26, if ($ length % 26) is returned directly )! = 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 unpackfrom 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 % 26) != 0:        return n    for i in range(0, length, 26):        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, port: %s\n" % (nid, ip, port)class DHTServer():    def __init__(self):        self.ufd = socket.socket(socket.AF_INET, socket.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(data)                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_node_qsize bigger, bandwith bigger, spped higher    dht = DHTServer()    dht.run()


Reply to discussion (solution)

Use $ msg when you run decode_nodes ($ msg)
Echo base64_encode ($ msg );
Output to see

This is not base64 encoding, but similar:
Unencoded: {"t": "aa", "y": "r", "r": {"id": "0123456789 abcdefghij", "nodes ": "def456... "}}
Encoded: d1: rd2: id20: 0123456789abcdefghij5: nodes9: def456... e1: t2: aa1: y1: re
This format

Nodeid, ip, and port are

Use $ msg when you run decode_nodes ($ msg)
Echo base64_encode ($ msg );
Output to see



There is a DHT protocol description: http://blog.csdn.net/xxxxxx91116/article/details/7970815

I am not interested in reading the protocol text.

The decoding format I gave you is in small order. if your data is in large order, check the pack function description and change it.

If you want me to check for you, follow what I said.

The moderator on the fourth floor is right. check the size and order.
Or what is the actual binary data with tcpdump.

Now we can get the correct IP address, but the port is still unsolvable, and it is indeed using the big-end sequence, but PHP only has these formats, each has tried, it is not correct, it is depressing...

So what is the solution? You can only paste the data.

Ah, I'm not willing to. it's like this:
For example, if a piece of data is sent from the server, the ip address is 188.19.238.146 and the port number is 6881. then, I can intercept the two-byte data of the port bit :?
The next step is decoding, which converts the network byte order to the port number: unpack ("n", $ port), but converts it to 57763, with unpack ("s", $ port) changed to-23583, and changed to 41953 with unpack ("S", $ port ).

I want you to encode the data you received with base64_encode. how can this problem be solved?

I want you to encode the data you received with base64_encode. how can this problem be solved?


Sorry, the data is as follows:
ZDE6cmQyOmlkMjA6daCpq0ZCdc6JP5An4ac4g4tlvPg1Om5vZGVzNDE2Oj4jyz4WVIOIxzAe2MXW4TWcH8dddZ6SRDktJ+7silGRA0YlQqlqucmPix2E6MZCvQ2ZY90lCzORZu5ZytoyWpBtKzh4PVNLMrz+Vo4exiqGYEUq3sV501VNWQ5XcqsXfXftr47cYrvZHsF4DCDFWnMcgC2Aq/DHVz00Wbxfm9qPqlsdaJ4um4dXnVtZ6BLCGgy42Pw3zVOnROrqVgpFb1J5g+BAxB2NOUMBBW7FQCyycNBojCpaDATl59Ekq4HpaHqD1gW057xisIRLgEp9f9VZvdr60s6C3CBNCX/OvoTfeJyY40k3SdswZ1lTimGVQRb7T7/VTO1rgXkZFTpuvAYbPCJaWUpbXcILoZh8A8H/qzKyirIM0v8lycJgFFdeiZR7bq+aPmxHVL1Scc6M3YMH17kiA8lK3l06cqN65EvX3/CuWJ4uw+fDhqSjVCkrwlpdQYO8k8mjkZhdVAaHCBUDxw9ESlvAXxuYGuFHYq2GV1BOhSYgmPJSaOzkghl0kq9lCiQvWUhr/ewsm/X/90CEXsTS45jet3HqWuZ2KcjVZTE6dDI6e8cxOnkxOnJl

Python has

    n = []    length = len(nodes)    if(length % 26) != 0:        return n
The length of the data you sent (after decoding) is 474.
Module 26 is 6
Please confirm that the data you provided is correct

Python has

    n = []    length = len(nodes)    if(length % 26) != 0:        return n
The length of the data you sent (after decoding) is 474.
Module 26 is 6
Please confirm that the data you provided is correct



Oh, sorry, this is the case. what we just gave is the obtained raw data, and then % 26 is the nodes data decoded by bencode. sorry, I forgot to make the data...

This is the raw data, including all the obtained data, such as y = r.
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 the bencode, that is, the data is divided into 26 bytes each, and 20 bytes of nid and 4 bytes of ip are extracted from the 26 bytes, 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, 26) 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, 26) 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 when I first intercepted it, it was wrong, so the result obtained was incorrect. thank you very much!

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.