简体   繁体   中英

UDP broadcast over crossover connection

I am attempting to broadcast a UDP packet over all NetworkInterfaces and receive the replies. While I am able to receive responses from the local network, a device connected via a crossover connection is not able receive a reply.

This is the code to get all Interfaces, which does return the crossover connection's NetworkInterface

    Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while(interfaces.hasMoreElements()){
            List<InterfaceAddress> iAddrs = interfaces.nextElement().getInterfaceAddresses();
            iAddrs.forEach(addr -> {
                if(addr.getBroadcast() != null){
                    System.out.println(addr.getBroadcast());

                    sendUDP(addr.getBroadcast());
                }
            });
        }

I then use this section of code to send the UDP packet and listen for responses.

    final DatagramSocket socket = new DatagramSocket(9800);
    socket.setBroadcast(true);
    socket.setSoTimeout(5000);
    final byte[] data = "A-UDP-BROADCAST".getBytes();
    byte[] buffer = new byte[1024];

    socket.send(new DatagramPacket(data, data.length, addr, 9800));

    while (true) {
        try {
            final DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
            socket.receive(packet);
            System.out.println(new String(packet.getData()));

        } catch (SocketTimeoutException e) {
            System.out.println("Timed out.");
            return;
        }
        buffer = new byte[1024];
    }

This must be an issue in this section of code, as when I send a packet with an external program such as PacketSender I am able to receive a reply.

What seems wrong to me about your code is how you bind both receiving and sending socket to the same port. Without setReuseAddress() one of the binds should fail. To fix that, simply change the first line in the second piece of code to use any free port:

final DatagramSocket socket = new DatagramSocket();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM