2010-03-01 117 views
1
import java.net.Socket; 
import java.io.IOException; 

public class Main { 


    public static void main(String[] args) { 
     String remote = "69.163.44.171"; 
     int i = 0; 
     do { 
     try { 
     Socket s = new Socket(remote,i); 
     System.out.println("Server is listening on port " + i+ " of " + remote); 
     s.close(); 

     } catch (IOException ex) { 
     System.out.println("Server is not listening on port " + i+ " of " + remote); 
    } 
     i++; 
     } while(i == 55000); 
} 

輸出:Java的端口掃描器

Server is not listening on port 0 of 69.163.44.171 
BUILD SUCCESSFUL (total time: 0 seconds) 

我使用while循環,因爲它速度更快,現在的問題是,爲什麼它只能掃描一個端口?

+0

While循環更快嗎? – 2010-03-01 21:03:28

+0

編譯器錯誤:在'while(i == 55000)'後面缺少';'並使用正常的'for'會使代碼更易讀... – 2010-03-01 21:44:36

+0

(a)這個程序是網絡綁定的。如何循環與其表現完全無關。 (b)這是一個'do'循環而不是'while'循環。 (c)比什麼更快?爲什麼? – EJP 2010-03-02 00:31:23

回答

2

您需要更改這個爲你而:

while(i <= 55000) 

目前你達到我(這是1)= 55000,所以你退出循環!

1

你是說while(i == 55000)代替while(i <= 55000)

2

這一部分:

} while(i == 55000) 

將重複循環只要i正是 55000.

由於i開始作爲0並且在那之後增加到1,它將永遠不會以va到達那個位置正好55000,因此永遠不會重新啓動循環。

3

好吧......多久一次確實您認爲條件while(i == 55000)會是true

0

在幾個答案中已經注意到條件錯誤,所以我不會重複。我可能會提出一個建議:如果您使用Selector和某些SocketChannels,而不是一次嘗試一個,則可能會使速度更快。 Here's一些閱讀材料。