如何从Android广播UDP数据包?

huangapple go评论118阅读模式
英文:

How to broadcast a UDP packet from Android?

问题

我需要从我的Android应用程序使用UDP向我的网络上的每个设备(以太网)广播一条消息。
但是,我不知道如何做这个,因为似乎没有关于如何发送广播消息的任何文档,只有关于如何使用IP地址发送到特定客户端的文档。

谢谢

英文:

I need to broadcast a message using UDP from my Android app to every device on my network (ethernet).
I'm lost on how to do this though because there doesn't seem to be any documentation on how to send a broadcast message, just ones on how to send to a specific client using IP addresses.

Thanks

答案1

得分: 5

这是一个有用的文档:google-AdroidUDP,这里是一个示例代码:

发送方:

public void sendBroadcast(String messageStr) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    try {
        DatagramSocket socket = new DatagramSocket();
        socket.setBroadcast(true);
        byte[] sendData = messageStr.getBytes();
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, getBroadcastAddress(), Constants.PORT);
        socket.send(sendPacket);
        System.out.println(getClass().getName() + "广播数据包已发送至:" + getBroadcastAddress().getHostAddress());
    } catch (IOException e) {
        Log.e(TAG, "IOException:" + e.getMessage());
    }
}

InetAddress getBroadcastAddress() throws IOException {
    WifiManager wifi = (WifiManager) mContext.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) & 0xFF);
    return InetAddress.getByAddress(quads);
}

接收方:

try {
    socket = new DatagramSocket(Constants.PORT, InetAddress.getByName("0.0.0.0"));
    socket.setBroadcast(true);

    while (true) {
        Log.i(TAG, "准备接收广播数据包!");

        byte[] recvBuf = new byte[15000];
        DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
        socket.receive(packet);

        Log.i(TAG, "收到数据包来自:" + packet.getAddress().getHostAddress());
        String data = new String(packet.getData()).trim();
        Log.i(TAG, "收到数据包;数据:" + data);

        Intent localIntent = new Intent(Constants.BROADCAST_ACTION)
            .putExtra(Constants.EXTENDED_DATA_STATUS, data);
        LocalBroadcastManager
            .getInstance(this)
            .sendBroadcast(localIntent);
    }
} catch (IOException ex) {
    Log.i(TAG, "出错:" + ex.getMessage());
}
英文:

Here is a useful doc: google-AdroidUDP, and here is a sample code:

Sender:

 public void sendBroadcast(String messageStr) {
     StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

     try {
         DatagramSocket socket = new DatagramSocket();
         socket.setBroadcast(true);
         byte[] sendData = messageStr.getBytes();
         DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, getBroadcastAddress(), Constants.PORT);
         socket.send(sendPacket);
         System.out.println(getClass().getName() + &quot;Broadcast packet sent to: &quot; + getBroadcastAddress().getHostAddress());
     } catch (IOException e) {
         Log.e(TAG, &quot;IOException: &quot; + e.getMessage());
     }
 }
 
 InetAddress getBroadcastAddress() throws IOException {
     WifiManager wifi = (WifiManager)    
     mContext.getSystemService(Context.WIFI_SERVICE);
     DhcpInfo dhcp = wifi.getDhcpInfo();


     int broadcast = (dhcp.ipAddress &amp; dhcp.netmask) | ~dhcp.netmask;
     byte[] quads = new byte[4];
     for (int k = 0; k &lt; 4; k++)
         quads[k] = (byte) ((broadcast &gt;&gt; k * 8) &amp; 0xFF);
     return InetAddress.getByAddress(quads);
 }

Receiver

      try {
          socket = new DatagramSocket(Constants.PORT, InetAddress.getByName(&quot;0.0.0.0&quot;));
          socket.setBroadcast(true);

          while (true) {
              Log.i(TAG,&quot;Ready to receive broadcast packets!&quot;);

              byte[] recvBuf = new byte[15000];
              DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
              socket.receive(packet);

              Log.i(TAG, &quot;Packet received from: &quot; + packet.getAddress().getHostAddress());
              String data = new String(packet.getData()).trim();
              Log.i(TAG, &quot;Packet received; data: &quot; + data);

              Intent localIntent = new Intent(Constants.BROADCAST_ACTION)
                  .putExtra(Constants.EXTENDED_DATA_STATUS, data);
              LocalBroadcastManager
                  .getInstance(this)
                  .sendBroadcast(localIntent);
          }
      }  catch (IOException ex) {
          Log.i(TAG, &quot;Oops&quot; + ex.getMessage());
      }

huangapple
  • 本文由 发表于 2020年9月23日 23:10:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/64030969.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定