LAN peer discovery

So, since the name might suggest that I am having some problems in my Java project. I want to do the following:

  • I have two computers running app X
  • There are also three more computers running app Y

I need to establish a connection between X and Y. For example, someone uses a computer running X, and after the discovrey process, they will be returned with a list of computers running Y and their IPs, and vice versa.

I did this using UDP broadcast, but sometimes it fails. Computers connect via WiFi, so basically through a router. In many cases, any of the X computers can see the Y objects through my UDP discovery method, but sometimes not if I don’t manually specify the IP, sometimes not even then.

Here is the code to detect servers listening on a specific port:

public static ArrayList<InetAddress> searchComputer() {
    ArrayList<InetAddress> targets = new ArrayList<InetAddress>();
    try {
        c = new DatagramSocket();
        c.setBroadcast(true);

        byte[] sendData = "DISCOVER_PC_SERVER_REQUEST".getBytes();
        try {
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, InetAddress.getByName("255.255.255.255"), 2005);
            c.send(sendPacket);
        } catch (Exception e) {}
        Enumeration interfaces = NetworkInterface.getNetworkInterfaces();

        while (interfaces.hasMoreElements()) {
            NetworkInterface networkInterface = (NetworkInterface) interfaces.nextElement();

            if (networkInterface.isLoopback() || !networkInterface.isUp()) {
                continue; 
            }

            for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
                InetAddress broadcast = interfaceAddress.getBroadcast();
                if (broadcast == null) {
                    continue;
                }

                try {
                    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, broadcast, 8888);
                    c.send(sendPacket);
                } catch (Exception e) { }
            }
        }
        byte[] recvBuf = new byte[15000];
        DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length);
        if (useInstant) {
            c.setSoTimeout(500);
        }
        else {
            c.setSoTimeout(4000); //EXECUTE THE WHILE FOR 4 SECONDS, THEN RETURN WHATEVER THE RESULTS ARE.
        }
        while (true) {
            c.receive(receivePacket);
            String message = new String(receivePacket.getData()).trim();
            if (message.equals("DISCOVER_PC_SERVER_RESPONSE")) {
//              return receivePacket.getAddress();
                targets.add(receivePacket.getAddress());
            }
        }
//      c.close();
    } catch (IOException ex){}
    return targets;
}

And here is my "server":

private void start_Discovery() throws Exception {
    //Keep a socket open to listen to all the UDP trafic that is destined for this port
    socket = new DatagramSocket(2005, InetAddress.getByName("0.0.0.0"));
    socket.setBroadcast(true);

    while (true) {
//      System.out.println(getClass().getName() + ">>>Ready to receive broadcast packets!");

        //Receive a packet
        byte[] recvBuf = new byte[15000];
        DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
        socket.receive(packet);

        //Packet received
//      System.out.println(getClass().getName() + ">>>Discovery packet received from: " + packet.getAddress().getHostAddress());
//      System.out.println(getClass().getName() + ">>>Packet received; data: " + new String(packet.getData()));

        //See if the packet holds the right command (message)
        String message = new String(packet.getData()).trim();
        if (message.equals("DISCOVER_ANDROID_SERVER_REQUEST")) {
            byte[] sendData = "DISCOVER_ANDROID_SERVER_RESPONSE".getBytes();

            //Send a response
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, packet.getAddress(), packet.getPort());
            socket.send(sendPacket);

//          System.out.println(getClass().getName() + ">>>Sent packet to: " + sendPacket.getAddress().getHostAddress());
        }
    }
}

Why sometimes they can’t see each other, even if they are connected to the same router? EXTRA: Is there a special case, X-computers are connected via LAN, and Y via Wi-Fi?

+4
source share
1 answer

, ?

Broadcasting UDP, . UDP () IP- . , .

, X- Y Wi-Fi?

, X-cmputers LAN Y Wi-Fi, . , . . , !

+1

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


All Articles