通过不断连接服务器的各个端口来测试哪个端口已经打开:
1.new android project:PortsScan
2.修改activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:orientation="vertical">
<Button android:layout_width="match_parent" android:layout_height="wrap_content"
android:text="@string/initScan" android:id="@+id/startScan"/>
<TextView
android:id="@+id/tvPorts"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/prompt" />
</LinearLayout>
3.实现MainActivity.java
package cn.yh.portsscan;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity{
private final String TAG = "PortsScan";
private TextView tvPorts;
private Button startScan;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
//将已经打开的端口号显示在TextView控件上
tvPorts.append(String.valueOf(msg.what) + ":ok\n");
Log.i(TAG, String.valueOf(msg.what));
super.handleMessage(msg);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvPorts = (TextView) findViewById(R.id.tvPorts);
startScan = (Button)findViewById(R.id.startScan);
startScan.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Thread thread = new Thread(new ScanPorts(1,1000));
thread.start();
Toast.makeText(MainActivity.this, "开始扫描", Toast.LENGTH_LONG).show();
}
});
}
class ScanPorts extends Thread{
private int minPort, maxPort;
public ScanPorts(int minPort, int maxPort) {
this.minPort = minPort;
this.maxPort = maxPort;
}
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=minPort; i<=maxPort; i++){
try{
Socket socket = new Socket();
SocketAddress socketAddress = new InetSocketAddress("192.168.1.100", i);
socket.connect(socketAddress,50);
handler.sendEmptyMessage(i);
socket.close();
}catch(Exception e){
Log.e(TAG, e.getMessage());
}
}
handler.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "扫描完成", Toast.LENGTH_LONG).show();
}
});
super.run();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
4.在AndroidManifest.xml开启Internet访问权限
<uses-permission android:name="android.permission.INTERNET"/>
运行结果:
其中192.168.1.100是我本机IP;