Or a question about PHP's binary stream

Source: Internet
Author: User
Tags sha1 unpack
or a binary streaming problem with PHP
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):
 $serv = new Swoole_server (' 0.0.0.0 ', 6882, swoole_process, SWOOLE_SOCK_UDP);
$serv->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.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, 10). 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, the total length is not equal to a multiple of 26 to return directly
if ($length% 26)! = 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-8

Import socket
From Hashlib Import SHA1
From random import Randint
From struct Import unpack
From socket import Inet_ntoa
From threading import Timer, Thread
From time import sleep
From collections Import Deque
From Bencode import Bencode, Bdecode

def 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:
Pass

if __name__ = = "__main__":
# max_node_qsize bigger, bandwith bigger, spped higher
DHT = Dhtserver ()
Dht.run ()

------to solve the idea----------------------
$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 [IP] = 177.183.234.200
[P] = 8080
)
Array
(
[n] = = Ü#?5 [IP] = 177.183.234.200
[P] = 8080
)
Array
(
[n] = = Ü#?5 [IP] = 177.183.234.200
[P] = 8080
)
Array
(
[n] = =?? Lè§? (á <>
[IP] = 101.204.70.62
[P] = 6881
)
Array
(
[n] = =?? Lè§? (á <>
[IP] = 101.204.70.62
[P] = 6881
)
Array
(
[n] = =?? Lè§? (á <>
[IP] = 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.
  • 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.