Search code examples
androidwifi-directbroadcasting

using UDP to broadcast on Wifi Direct


i'm new to wifi direct and i want to be able to broadcast a message, because i have a timeline and when i click the Post button i want all the connected devices have that message displayed on their timeline. I am able to send data peer to peer.I have searched about this subject and i found using UDP is a good choice but i don't know how to implement it in wifi direct.

I found this code that uses UDP on wifi to Get the Broadcast Address

InetAddress getBroadcastAddress() throws IOException {
WifiManager wifi = mContext.getSystemService(Context.WIFI_SERVICE);
DhcpInfo dhcp = wifi.getDhcpInfo();
// handle null somehow

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) & 0xFF);
return InetAddress.getByAddress(quads);} 

and this for Sending and Receiving UDP Broadcast Packets

DatagramSocket socket = new DatagramSocket(PORT);
socket.setBroadcast(true);
DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length(),
getBroadcastAddress(), DISCOVERY_PORT);
socket.send(packet);

byte[] buf = new byte[1024];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);

could you please help me and explain to me how it works thanks in advance.


Solution

  • One solution is to Multicast a packet to a Multicast Group. All the devices join a Multicast IP and the sender sends the packet to that Multicast IP. Make sure IP you assign falls in the range of Multicast IPs. When dealing with Multicasting, the device needs to acquire a Multicast Lock. Note that since Multicast is based on UDP, some errors in transmissions are expected.

    AsyncTask Class for Devices that will receive the packet:

    import java.io.IOException;
    import java.net.DatagramPacket;
    import java.net.InetAddress;
    import java.net.MulticastSocket;
    import java.net.UnknownHostException;
    
    import android.content.Context;
    import android.net.wifi.WifiManager;
    import android.net.wifi.WifiManager.MulticastLock;
    import android.os.AsyncTask;
    import android.util.Log;
    import android.view.View;
    import android.widget.TextView;
    
    public class ReceiverMulticastAsyncTask extends AsyncTask<Void, Integer ,String > {
    
        @Override
        protected String doInBackground(Void... params) {
    
            //Acquire the MulticastLock
            WifiManager wifi = (WifiManager)  getActivity().getSystemService(Context.WIFI_SERVICE);
            MulticastLock multicastLock = wifi.createMulticastLock("multicastLock");
            multicastLock.setReferenceCounted(true);
            multicastLock.acquire();
    
            //Join a Multicast Group
            InetAddress address=null;
            MulticastSocket clientSocket=null;
            try {
                clientSocket = new MulticastSocket(1212);
                address = InetAddress.getByName("224.0.0.1");
                clientSocket.joinGroup(address);
            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
    
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();        
            }
            DatagramPacket packet=null;           
            byte[] buf = new byte[1024];
            packet = new DatagramPacket(buf, buf.length);
            //Receive packet and get the Data
            try {
                clientSocket.receive(packet);
                byte[] data = packet.getData();
                Log.d("DATA", data.toString()+"");
    
            } catch (Exception e) {
                e.printStackTrace();
    
            }
            multicastLock.release();
    
            try {
                clientSocket.leaveGroup(address);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            clientSocket.close();
            return "";
        }
    
        @Override
        protected void onPostExecute(String result) {
            //do whatever...
        }
    }
    

    AsyncTask Class for Device that will send the packet:

    import java.io.IOException;
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    import java.net.InetAddress;
    import java.net.MulticastSocket;
    import java.net.SocketException;
    import java.net.UnknownHostException;
    
    import android.content.Context;
    import android.net.wifi.WifiManager;
    import android.net.wifi.WifiManager.MulticastLock;
    import android.os.AsyncTask;
    import android.util.Log;
    import android.view.View;
    import android.widget.TextView;
    
    public class SenderMulticastAsyncTask extends AsyncTask<Void, Integer, String> {
    
        @Override
        protected String doInBackground(Void... params) {
    
            int port =1212;
            DatagramSocket socket=null;
            try {
                socket = new DatagramSocket(port);
            } catch (SocketException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            InetAddress group = null;
            try {
                group = InetAddress.getByName("224.0.0.1");
            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                socket.close();
                e.printStackTrace();
            }
    
            //Sending to Multicast Group
            String message_to_send ="Test";
            byte[] buf = message_to_send.getBytes();
            DatagramPacket packet = new DatagramPacket(buf, buf.length, group, port);
            try {
                socket.send(packet);
                Log.d("Send", "Sending Packet");
            } catch (IOException e) {
                // TODO Auto-generated catch block
                socket.close();
                e.printStackTrace();
            }
    
            socket.close();
            return "";
        }
    
        @Override
        protected void onPostExecute(String result) {
            //do whatever ...
        }
    }