How to parse proxy package in java?

I am trying to create a basic proxy server 4, and I need to parse the package and extract its information, which looks like this:

1 byte (version)
1 byte (command)
2 byte (port)
4 byte (ip)
X byte (userID, builds a string by looping until '\0' is found)

Here is my code:

InputStream reader = socket.getInputStream();

byte[] ver  = new byte[1];
byte[] cmd  = new byte[1];
byte[] port = new byte[2];
byte[] ip   = new byte[4];

reader.read(ver, 0, 1);  //should be: 4
reader.read(cmd, 1, 1);  //should be: 1
reader.read(port, 2, 2); //should be: 00, 80
reader.read(ip, 4, 4);   //should be: 217, 70, 182, 162

Here is the answer I get from my code: [4, 1, 0, 80, -39, 70, -74, -94]

For some reason, the part of the IP that I get is always wrong, I really don't know why. My second problem would be: is there a simple and clean way to get the last line of userID without creating a messy loop that could hang forever if the byte was \0not found?

Thank.

+4
source share
2 answers

DataInputStream. ints, shorts, longs , .

+4

, , - - , , -128 127 Java.

, , () []...

, , (ip) --- , , . , , , int [],

int[] ip   = new int[4];
byte[] temp = new byte[4];
reader.read(temp, 4, 4);   //should be: 217, 70, 182, 162
for(int i=0;i<temp.length;i++)
{
 if(temp[i]<0)
 ip[i]=(int)(256+temp[i]);  // careful here
 else
 ip[i]=(int)temp[i];
}

, , , String-part String.length().

 int len = userID.length();  // assume user-id would be String type
 userid = new byte[len];   // notice the difference between userid and userID
 reader.read(userid,0,len);
 // I am confused as to how are you reading input from user,
 // if you clarify further,I'll update my answer...
+2

All Articles