Android scan subnet

I am currently writing a small test application for Android and am facing a small (large) problem with the emulator.

The code that goes out and scans the local subnet for computers that run my part of the server returns nothing! This code works fine on the desktop, so I know that something is wrong inside my emulator.

I had to reschedule the IP scan first because I cannot determine the IP address in the emulator, so I know that I, at least, am looking at the correct range.

Summary. How to connect to servers via sockets from my emulator on a local subnet?

Thanks everyone!

Here's the requested code:

public static ArrayList<String> serviceScanner() {
    ArrayList<String> servers = new ArrayList<String>();

    // Get the IP of the local machine
    String iIPv4 = "";
    String test = "";


    //getLocalIpAddress();
    //System.out.println(test);

    try {
        // Get localhost
        InetAddress addr = InetAddress.getLocalHost();

        // Get IP Address
        byte[] ipAddr = addr.getAddress();

        iIPv4 = addr.toString();
        iIPv4 = iIPv4.substring(iIPv4.indexOf("/") + 1);
        iIPv4 = "10.0.2.1";
    } catch (UnknownHostException e) {
        // Exception output
    }
    // IP stuff.
    String IPv4Start = "", IPv4End = "";
    iIPv4 = iIPv4.substring(0, iIPv4.lastIndexOf("."));
    iIPv4 += ".";
    IPv4Start = iIPv4 + "1";
    IPv4End = iIPv4 + "254";


    PrintWriter out = null;
    BufferedReader in = null;

    // Loop to scan each address on the local subnet
    for (int i = 1; i < 255; i++) {

        try {
            System.out.println(iIPv4+i);
            Socket mySocket = new Socket();
            SocketAddress address = new InetSocketAddress(iIPv4 + i, port);

            mySocket.connect(address, 5);

            out = new PrintWriter(mySocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(
                    mySocket.getInputStream()));
            out.println("Scanning!");
            String fromServer;
            while ((fromServer = in.readLine()) != null) {
                System.out.println("Server: " + fromServer);
                if (fromServer.equals("Server here!")) {
                    servers.add(iIPv4 + i);
                    mySocket.close();
                    break;
                }
            }
            mySocket.close();
            out.close();
            in.close();

        } catch (UnknownHostException e) {
        } catch (IOException e) {
        }
    }
    return servers;
}

}

+3
source share
1 answer
+3

Source: https://habr.com/ru/post/1794465/


All Articles