關於PHP中的pack問題,dht的進位流要怎麼才能編碼解碼?

來源:互聯網
上載者:User
我嘗試用PHP來做一個dht爬蟲,由於資料的傳輸使用的是bencode,這個是沒問題的,可以正確編碼解碼,但是其中如果發送find_node資料,擷取到的資料中有一個nodes,這是一個使用struct結構的二進位流編碼的資料,根據dht協議所說,是:20位元組的node id + 4位元組的ip + 2位元組的連接埠,我看過python裡的編碼解碼方式,但無法轉換為php中的,python中是這樣轉換的:

def decodeNodes(nodes):    """    把收到的nodes轉成例表.     資料格式: [ (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):    """    "編碼"nodes 與decodeNodes相反    """    n = []    for node in nodes:        n.extend([node.nid, dottedQuadToNum(node.ip), node.port])    return pack("!" + "20sIH" * len(nodes), *n)


請問在PHP裡要如何才能夠這樣轉換呢?


回複討論(解決方案)

20位元組的node id : a20 或 A20 如果是用空格充填不足就用後者
4位元組的ip: L ip 地址用 ip2long 轉換成無符號長整形數
2位元組的連接埠: S

打包
$s = pack('a20LS', $nodeid, ip2logn($ip), 456);
解包
$d = unpack('a20nodeid/Lip/Sport', $s);
$d['ip'] = logn2ip($d['ip']);
print_r($d); //就清楚了

20位元組的node id : a20 或 A20 如果是用空格充填不足就用後者
4位元組的ip: L ip 地址用 ip2long 轉換成無符號長整形數
2位元組的連接埠: S

打包
$s = pack('a20LS', $nodeid, ip2logn($ip), 456);
解包
$d = unpack('a20nodeid/Lip/Sport', $s);
$d['ip'] = logn2ip($d['ip']);
print_r($d); //就清楚了



非常感謝,解決了
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    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.