7

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.

lna1994
  • 73
  • 1
  • 3
  • I have a solution where you can multicast a packet to a multicast group. So if all the devices join a multicast IP. Then sending one UDP packet to that multicast IP will be received by all the devices. Let me know if you want me to elaborate more on it. – Ziad Halabi Apr 18 '15 at 05:49
  • @ZiadHalabi yeah please elaborate, and if you code give some sample code that would be great – lna1994 Apr 18 '15 at 06:55
  • @Ina1994 Please edit your question so that it asks a more general broadcasting question in WiFi Direct. – Ziad Halabi Apr 18 '15 at 07:22

2 Answers2

4

In Android's Wi-Fi P2P there is a concept of "group owner", which is the device that acts as an access point. For the current API the group owner's IP address seems to be set to 192.168.49.1, which I think is hard-coded somewhere. A quick guess on the broadcast address for the group's network will be 192.168.49.255. For all (of a few) devices I have tested so far that turned out to be the case.

Butshuti
  • 61
  • 4
  • for my real device testing, only group owner able to receive broadcast packet, other device cannot, it's SAMSUNG c7 Android 8. – Amos Aug 30 '23 at 03:16
1

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 ...
    }
}
Ziad Halabi
  • 964
  • 11
  • 31
  • i dont understand how can i implement this code in wifi direct – lna1994 Apr 18 '15 at 08:36
  • i mean the `wifi` variable is of type `WifiManager` not `WifiP2pManager` and i can't use `createMulticastLock` with type of `WifiP2pManager` – lna1994 Apr 18 '15 at 08:39
  • After establishing the WiFi Direct connection you can execute these AsyncTask classes. When the WiFi Direct connection is established, the relation between the devices and the groupowner is the same as when dealing with an Access Point. For instance in a button listener you can write this: new SenderMulticastAsyncTask.execute(); – Ziad Halabi Apr 18 '15 at 08:41