开发者

UDP broadcast on Java doesn't work

开发者 https://www.devze.com 2023-04-06 14:47 出处:网络
I\'m trying to send a UDP broadcast on IP address \"255.255.255.255\" for device discovery in my network. The program executes, but I don\'t see anything in Wireshark. when I\'m changing the IP addres

I'm trying to send a UDP broadcast on IP address "255.255.255.255" for device discovery in my network. The program executes, but I don't see anything in Wireshark. when I'm changing the IP address to a known IP in开发者_开发技巧 my network, I can see the packets in Wireshark. what's going on ?

This is my code:

public static void main(String args[]) throws Exception
{
    String Broadcastaddress = new String("255.255.255.255");
    int port = 9876;
    DatagramSocket serverSocket = new DatagramSocket();
    serverSocket.setBroadcast(true);
    InetAddress IPAddress = InetAddress.getByName(Broadcastaddress);
    System.out.println("Sending Discovery message to " + IPAddress + "Via UDP port " + port);

    byte[] sendData = new byte[4];
    sendData[0] = 'F';
    sendData[1] = 'I';
    sendData[2] = 'N';
    sendData[3] = 'D';

    DatagramPacket sendPacket = new DatagramPacket(sendData,sendData.length,IPAddress,port);

    while (true)
    {
        serverSocket.send(sendPacket);
        System.out.println("Packet sent");
    }


}


OK, I found an answer. Windows 7 doesn't support 255.255.255.255 broadcasts anymore, apparently it was an opening to various threats. To broadcast, one needs to use a different approach.

This is a small explenation from Wikipedia:

The broadcast address for an IPv4 host can be obtained by performing a bitwise logical OR operation between the bit complement of the subnet mask and the host's IP address. Example: to broadcast a packet to an entire IPv4 subnet using the private IP address space 100.16.0.0/12, which has the subnet mask 255.240.0.0, the broadcast address is: 100.16.0.0 | 0.15.255.255 = 100.31.255.255.

A special definition exists for the IP broadcast address 255.255.255.255. It is the broadcast address of the zero network or 0.0.0.0, which in Internet Protocol standards stands for this network, i.e. the local network. Transmission to this address is limited by definition, in that it is never forwarded by the routers connecting the local network to the Internet.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号