2013-03-21 105 views
0

我想在Android上製作一個端口掃描器,而且我有點卡住了。我想查看一個端口是否在路由器/默認網關上打開,但似乎沒有任何工作。我嘗試使用可達,但我覺得這可能是錯誤的事情。Android端口掃描器

import java.net.InetAddress; 
import java.net.UnknownHostException; 

import android.app.Activity; 
import android.content.Context; 
import android.content.Intent; 
import android.content.IntentFilter; 
import android.net.DhcpInfo; 
import android.net.wifi.WifiInfo; 
import android.net.wifi.WifiManager; 
import android.os.Bundle; 
import android.widget.TextView; 

public class portscan extends Activity { 

String targetHost; 
public int startPort = 1; //(for uses in later programming) 
public int endPort = 1000; 
private Intent scanIntent; 
InetAddress targetAddress; 
String targetHostName; 
WifiManager networkd; 
DhcpInfo details; 
public String gateway; 
TextView GW; 


protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    try { 
    setContentView(R.layout.port); 
    GW = (TextView)findViewById(R.id.gateway); 
    networkd = (WifiManager) getSystemService(Context.WIFI_SERVICE); 
    details = networkd.getDhcpInfo(); 
    String test = intToIp(details.gateway); 

    gateway = "Default Gateway: "+String.valueOf(details.gateway); 
    boolean isAvailable = false; 

     isAvailable = InetAddress.getByName(test).isReachable(80); //trying to see if port open 
     if (isAvailable == true) { 
      GW.setText("port 21 is up"); 

     } 
    } catch (Exception e) { 

    } 


} 

public String intToIp(int i) { //this converts the DHCP information (default gateway) into a readable network address 

     return (i & 0xFF)+ "." + 
       ((i >> 8) & 0xFF) + "." + 
       ((i >> 16) & 0xFF)+ "." + 
       ((i >> 24) & 0xFF); 
    } 
+0

看着'isReachbable(80)',我覺得有必要指出的是,該參數是'超時value',_not端口number_。但不要介意,只是不要使用它。 – 2013-03-21 20:14:02

回答

0

使用下面的代碼可以添加超時。

try { 
    Socket socket = new Socket(); 
    SocketAddress address = new InetSocketAddress(ip, port); 
    socket.connect(address, TIMEOUT); 
    //OPEN 
    socket.close(); 
} catch (UnknownHostException e) { 
    //WRONG ADDRESS 
} catch (SocketTimeoutException e) { 
    //TIMEOUT 
} catch (IOException e) { 
    //CLOSED 
} 
1

不要使用isReachable,這並不意味着端口掃描(和不可靠爲別的太多,真的)。

對於端口掃描,您使用sockets。僞示例:

for (int port = 0; port <= 9999; port++) 
    { 
     try 
     { 
      // Try to create the Socket on the given port. 
      Socket socket = new Socket(localhost, port); 

      // If we arrive here, the port is open! 
      GW.setText(GW.getText() + String.Format("Port %d is open. Cheers!\n", port)); 

      // Don't forget to close it 
      socket.close(); 
     } 
     catch (IOException e) 
     { 
      // Failed to open the port. Booh. 
     } 
    } 
+0

謝謝你,我會嘗試儘快使用它,但我必須問我嘗試過這樣的事情,沒有任何端口在192.168.0.1(默認門的方式)上打開,我知道是一個plop負載?你的代碼是否會在讀取默認網關端口時工作? – user215470 2013-03-21 22:05:25