Android:扫描TCP套接字服务器IP(端口已知)

时间:2014-06-25 14:32:56

标签: android arrays

我正在扫描我的子网,寻找端口7打开并使用并行线程的套接字服务器。我总是在服务器端看到“连接”和“断开连接”的镜头,所以基本代码应该没问题。

但是如何在阵列中收集找到的(成功连接的)服务器IP?

非常感谢任何帮助!

public class MainActivity extends Activity{
Button buttonConnect;

Socket socket = null;
int port = 7;
int timeout = 200;

final ExecutorService es = Executors.newFixedThreadPool(20);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    buttonConnect = (Button) findViewById(R.id.button1);

    buttonConnect.setOnClickListener(buttonConnectOnClickListener);

}

Button.OnClickListener buttonConnectOnClickListener = new Button.OnClickListener() {

    @Override
    public void onClick(View v) {

        String iIPv4 = "192.168.0.1";
        iIPv4 = iIPv4.substring(0, iIPv4.lastIndexOf("."));
        iIPv4 += ".";

        for (int i = 1; i < 255; i++) {
            findSocket(es, iIPv4 + i, port, timeout);
        }
    }
};

public static Future<Boolean> findSocket(final ExecutorService es,
        final String ip, final int port, final int timeout) {
    return es.submit(new Callable<Boolean>() {
        @Override
        public Boolean call() {
            try {
                Socket socket = new Socket();
                socket.connect(new InetSocketAddress(ip, port), timeout);
                socket.close();
                return true;
            } catch (Exception ex) {
                return false;
            }
        }
    });
}

}

1 个答案:

答案 0 :(得分:0)

ArrayList<String> arrayList = new ArrayList<String>();

然后在try

之前的findSocket return true;块中
arayList.add(ip);