2014-11-23 34 views
4

我試着去建立一個基本的代理4服務器,我必須分析數據包並提取其信息,看起來像這樣:如何在java中解析代理socks數據包?

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

這裏是我到目前爲止的代碼:

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 

這裏的迴應我從我的代碼得到:[4, 1, 0, 80, -39, 70, -74, -94]

由於某些原因,我得到的IP部分總是錯的,我真的不知道爲什麼。我的第二個問題是:是否有一種簡單而乾淨的方法來獲取最後一個userID字符串部分,而不必構建一個混亂的循環,如果沒有找到\0字節,可能會永遠掛起來,直到永遠懸掛?

謝謝。

+0

你可以轉儲'Stream'數據'byte-by-'byte'來查看它包含的內容嗎? – 2014-11-23 09:58:22

+0

@BoristheSpider:[4,1,0,80,-39,70,-74,-94,0,0](沒有用戶標識) – Heidi 2014-11-23 10:03:40

回答

4

把它全部扔掉,並使用DataInputStream的方法。他們會給你ints,shorts,longs和完全讀取的字節數組,併爲你處理網絡字節排序。

+0

謝謝。我會給'DataInputStream'一個嘗試和一點研究,然後回覆你。 – Heidi 2014-11-23 10:35:10

+0

我同意這是大勢所趨,現在正在使用!但是,請不要只介紹術語,總是留下一些例子。你可能會爲此獲得降價! – 2014-11-23 10:35:34

+0

@shekharsuman不要把話放進我的嘴裏。我沒有談及'一般趨勢',這個解決方案自1996年以來一直在Java中使用,而不僅僅是'現在'。我希望任何有能力的計算機程序員都能根據這些信息設計出正確的解決方案。 – EJP 2014-11-23 10:38:13

2

您收到的第一個問題全是因爲字節溢出,因此轉爲負數,因爲字節範圍從-128到127。

檢查this question我問在這個論壇上了解魔術的byte [] ...的(問題)

嚴重的是,如果這是你去年場的方法,(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.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... 
+0

謝謝,我會試一試'int []'您。至於我的問題的第二部分,userID字符串是代理客戶端自己設置的。除了等待'\ 0'字節外,我無法確定它們的大小。 – Heidi 2014-11-23 10:28:42

+0

爲什麼downvote ???請留下澄清。 – 2014-11-23 10:32:15

+0

完全不可能寫出正確的網絡代碼,而忽略read()方法返回的值。 – EJP 2014-11-23 10:32:44