Android sockets send broadcast packets to those pits

Source: Internet
Author: User

The socket broadcast packet is often used for mutual discovery and messaging between two devices within the LAN, and is often encountered during Android application development, such as between two Android devices, smart hardware such as Android and the bracelet, Between Android and Windows computer and so on.


This article focuses on programming considerations and workarounds for developing broadcast package programs using sockets in Android.


Here is a sample code for an Android send broadcast packet:


Datagramsocket socket = new Datagramsocket (8000); Socket.setbroadcast (true); InetAddress addr = Inetaddress.getbyname (" 255.255.255.255 "); byte[] buffer =" Hello World ". GetBytes ();D atagrampacket packet = new Datagrampacket (buffer, Buffer.length);p acket.setaddress (addr);p acket.setport (8086); socket.send (packet);


Here is an analysis of the areas to note:


1. Do not send broadcast packets in the main thread


Of course, this Android developer should be aware that it is not possible to perform any network access related operations in the UI thread, because the broadcast packet is sent to a network operation, and therefore must be executed in a separate thread.


2. "255.255.255.255" is not recommended for broadcast addresses


In the above code, the target address of the broadcast packet is set to "255.255.255.255", in fact, this is not a recommended practice.


"255.255.255.255" is a limited broadcast address, often used to send when the computer does not know its IP address, such as when the device starts to request an address to the DHCP server, etc., in general, the router does not forward a broadcast packet targeted to a limited broadcast address.


Also, some router/wi-fi hotspots do not support this broadcast address (for example, when using an Android phone as a Wi-Fi hotspot), so the "Enetunreach (Network is unreachable)" exception appears in the program, so , in order to ensure that the program successfully send broadcast packets, we recommend the use of direct broadcast address, for example: The current IP address is 192.168.1.100, the subnet mask is 255.255.255.0 case, Broadcast address is: 192.168.1.255, (the specific calculation method here does not expand, you can refer to the computer network related books).


So, how to get the direct broadcast address of this network segment, here is the StackOverflow above has a Daniel share code:


Public static inetaddress getbroadcastaddress (Context context)  throws  unknownhostexception {    wifimanager wifi =  (WifiManager) Context.getsystemservice (Context.wifi_service);    dhcpinfo dhcp =  Wifi.getdhcpinfo ();     if (Dhcp==null)  {         return inetaddress.getbyname ("255.255.255.255");    }     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);} 


Use this function directly to get the correct "broadcast address", which can be set to the Datagrampacket object by Setaddress function.


3. Broadcast address when Android is set as a Wi-Fi hotspot


This is a bigger pit, when the Android device is set up as a Wi-Fi hotspot, the above function gets the address "0.0.0.0", so we need to explore when the Android device is set as a Wi-Fi hotspot, how much is its IP address?


Someone studied the android underlying source discovery, when the Android device is set as a Wi-Fi hotspot, its IP address is hardcode write dead in the source code, the address is: "192.168.43.1", the corresponding broadcast address is: " 192.168.43.255 "


To do this, we need to write a function to determine whether the current Android phone is in Wi-Fi hotspot mode, if so, you should use this broadcast address given above, here is a code example:


protected static boolean iswifiapenabled (Context  Context)  {    try {        wifimanager  manager =  (Wifimanager) context.getsystemservice (context.wifi_service);           method method = manager.getclass (). GetMethod (" Iswifiapenabled ");        return  (Boolean) Method.invoke (manager);     }    catch  (nosuchmethodexception e)  {         e.printstacktrace ();     }    catch   (illegalaccessexception | illegalargumentexception | invocationtargetexception  e)   {        e.printstacktrace ();}     return false;} 


The Android SDK does not open the API to determine whether it is in hotspot mode, so we need to get it through reflection, in addition, pay attention to adding permissions:


<uses-permission android:name= "Android.permission.ACCESS_WIFI_STATE"/>


4. Summary


The code involved in this article is encapsulated in a Broadcaster.java file that can be downloaded from the last attachment in the blog post, or can be downloaded from the following address:


Https://github.com/Jhuster/Android/blob/master/Socket/Broadcaster.java


About the Android socket to send a broadcast packet of those pits to summarize here, have any questions or suggestions welcome message or letter [email protected] exchange, or follow my Sina Weibo @ Lu _ June get the latest articles and information.



This article is from the "Shadow Three People" blog, please be sure to keep this source http://ticktick.blog.51cto.com/823160/1707858

Android sockets send broadcast packets to those pits

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.