Search code examples
javaudpbroadcast

how to set the source address of udp broadcast?


I have this code to send out a broadcast message over a lan and it was working fine until I installed a virtual machine and i now have a virtual network adapter.

  String address = "255.255.255.255";
    try {
        packet.setAddress(InetAddress.getByName(address));
        packet.setPort(59123);
        DatagramSocket socket = new DatagramSocket();
        socket.setBroadcast(true);
        socket.send(packet);
        ...

Now when I try to do the broadcast Wireshark is showing the message being sent from 192.168.56.1 (ip address of virtual adapter)

How would i go about setting the adapter I'd like to use for sending the message?


Solution

  • Use the DatagramSocket constructor which takes the local inet address to bind to.