p2p - How to decode Compact node info in java? -


i decoded nodes of find_node response router.bittorrent.com string, , sent find_node request decoded "nodes" , never reviced find_node response "nodes", doubt way decode "node" wrong, code:

        byte[] nodesbytes = ((string)nodes).getbytes();         bytebuffer buffer = bytebuffer.wrap(nodesbytes);         int size = nodesbytes.length / 26;         (int = 0; < size; i++) {              byte[] bytes = new byte[26];             byte[] nodeidbytes = arrays.copyofrange(bytes, 0, 20);             byte[] ipbytes = arrays.copyofrange(bytes, 20, 24);             byte[] portbytes = arrays.copyofrange(bytes, 24, 26);             routingtable.routingnode routingnode = new routingtable.routingnode();             try {                 routingnode.nodeid = nodeidbytes;                 routingnode.ip = inetaddress.getbyaddress(ipbytes);                 routingnode.port = (((((short)portbytes[1]) << 8) & 0xff00) + (((short)portbytes[0]) & 0x00ff));             } catch (unknownhostexception e) {                 e.printstacktrace();             }             send(routingnode);         } 

and decode string code is

  private static string decodestring(bytebuffer bytebuffer) {     try {         stringbuilder buffer = new stringbuilder();         int type = bytebuffer.get();         buffer.append((char) type);         {             byte = bytebuffer.get();             if (a == separator) {                 break;             } else {                 buffer.append((char) a);             }         } while (true);          int length = integer.parseint(buffer.tostring());         byte[] bytes = new byte[length];         bytebuffer.get(bytes);         string value = new string(bytes, "utf-8");         logger.debug(value);         return value;     } catch (exception e) {         logger.error("", e);     }     return ""; } 

any problem there ?

ps: send() function work well.

((string)nodes).getbytes();

that assumes particular encoding, may not appropriate case. depends on bdecoder implementation you're using does. ideally should use method returns byte[] or bytebuffer directly bencoded data, without going through string

routingnode.port = (((((short)portbytes[1]) << 8) & 0xff00) + (((short)portbytes[0]) & 0x00ff));

you should use | instead of +. additionaly short signed type in java ports in unsigned range of 0-65535, should expand int instead. , network format bigendian, significant bits of port come in 0th byte , lower half in 1st one, got backwards too.

using bytebuffer instead of byte[] in own implementation can make far less errorprone since allows short directly , convert unsigned int.


Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -