nrubin29
nrubin29

Reputation: 1612

Get All Devices on WiFi Network with Java

I am attempting to discover all of the devices on the WiFi network to which my device is connected. This is plain Java, not Android. I need to search through each device to see if it has a particular port open. I will connect to the first device I find that matches this criteria through a Socket, so I'll need its IP address. I am essentially attempting to write the following code:

for (WiFiDevice device : WiFi.getConnectedDevices()) {
    if (device.hasPortOpen(1234)) {
        this.socket = new Socket(device.getIPAddress(), 1234);
    }
}

Upvotes: 2

Views: 12373

Answers (2)

nrubin29
nrubin29

Reputation: 1612

Here is my answer, which works well on my Mac but is a bit hacky.

Socket socket = new Socket();

try {
    Process process = Runtime.getRuntime().exec("arp -i en0 -a -n");
    process.waitFor();
    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

    while (reader.ready()) {
        String ip = reader.readLine();
        ip = ip.substring(3, ip.indexOf(')'));

        try {
            socket.connect(new InetSocketAddress(ip, 1234), 1000);
            System.out.println("Found socket!");
        } catch (ConnectException | SocketTimeoutException ignored) {

        }
    }

    if (socket == null) {
        System.err.println("Could not find socket.");
    }
} catch (Exception e) {
    e.printStackTrace();
}

Upvotes: 0

Rahat Mahbub
Rahat Mahbub

Reputation: 2987

How about this hacky solution:

import java.net.InetAddress;
import java.net.Socket;

public class Main {
    public static void main(String[] args) {

        int timeout=500;
        int port = 1234;

        try {
            String currentIP = InetAddress.getLocalHost().toString();
            String subnet = getSubnet(currentIP);
            System.out.println("subnet: " + subnet);

            for (int i=1;i<254;i++){

                String host = subnet + i;
                System.out.println("Checking :" + host);

                if (InetAddress.getByName(host).isReachable(timeout)){
                    System.out.println(host + " is reachable");
                    try {
                        Socket connected = new Socket(subnet, port);
                    }
                    catch (Exception s) {
                        System.out.println(s);
                    }
                }
            }
        }
        catch(Exception e){
            System.out.println(e);
        }
    }

    public static String getSubnet(String currentIP) {
        int firstSeparator = currentIP.lastIndexOf("/");
        int lastSeparator = currentIP.lastIndexOf(".");
        return currentIP.substring(firstSeparator+1, lastSeparator+1);
    }
}

Upvotes: 1

Related Questions