我正在尝试在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 :(得分: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.
}
}
答案 1 :(得分:1)
使用下面的代码可以添加超时。
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
}