user8404505
user8404505

Reputation:

Datagram socket asks for destination address

When send a data using Datagram socket connection it fires exception:

Destination address is null

DatagramSocket ds = new DatagramSocket(1050);
                ds.setBroadcast(true);
                InetAddress broadcastAdress = getBroadcastAdd();
                DatagramPacket pack = new DatagramPacket(data, data.length, broadcastAdress, 1050);
                ds.send(pack);
                ds.close();

Why does it say that if UDP means broadcasting, so the receiver is everyone, no particular address?

What address must be used and where should it be placed?

Well I was using that code to get that address:

private InetAddress getBroadcastAdd() throws UnknownHostException {
    WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    DhcpInfo dhcp = wifi.getDhcpInfo();
    int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
    byte[] quads = new byte[4];
    for (int k = 0; k < 4; k++)
        quads[k] = (byte) (broadcast >> (k * 8));
    return InetAddress.getByAddress(quads);
}

But I still have the null Exception:

image

Upvotes: 1

Views: 309

Answers (1)

C&#233;dric Julien
C&#233;dric Julien

Reputation: 80771

If you want to use UDP to broadcast a message, then you should use the setBroadcast on your socket, and use the broadcast address (an address is always needed, even in case of broadcasting).

DatagramSocket udpSocket = new DatagramSocket(1050);
udpSocket.setBroadcast(true);
InetAddress broadcastAdress = getAdressBroadcast();
DatagramPacket pack = new DatagramPacket(data, data.length, broadcastAdress, 1050);
udpSocket.send(pack);

With the getAddressBroadcast like this :

public static String getAdressBroadcast() throws SocketException {
    System.setProperty("java.net.preferIPv4Stack", "true");
    for (Enumeration<NetworkInterface> networkInterfaceEnum = NetworkInterface.getNetworkInterfaces(); networkInterfaceEnum.hasMoreElements();) {
        NetworkInterface networkInterface = networkInterfaceEnum.nextElement();
        if (!networkInterface.isLoopback()) {
            for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
                return interfaceAddress.getBroadcast().toString().substring(1);
            }
        }
    }
    return null;
}

As a side note, do not forgot to do those action (networking operation) should not be done in the main activity thread, but in an Async task

Upvotes: 2

Related Questions