Search code examples
c#androidsocketsxamarin.android

UDP broadcasting dont work on android phone hotspot C#


i'm trying to broadcast a udp package from one cell-phone to another in xamarin android i have this code on sender:

                Socket brd = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                brd.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
                IPEndPoint ipe = new IPEndPoint(IPAddress.Broadcast, 9050);
                string host =  Dns.GetHostName();
                byte[] data = Encoding.Unicode.GetBytes(host);
                brd.SendTo(data, ipe);

and i have this code on receiver device:

            Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
            sock.Bind(iep);
            EndPoint ep = iep;
            byte[] data = new byte[1024];
            int recv = sock.ReceiveFrom(data, ref ep);
            string stringData = Encoding.Unicode.GetString(data, 0, recv);

this works fine when two device are on the my wifi-router network, but when i use hotspot on one device the other one doesn't receive anything!

i tried the same code on C# console and connect my pc to modem the packets received fine but when pc is connected to phone hotspot the broadcast doesn't get received again like nothing happening!

what did i do wrong? i there a better approach for this thing?


Solution

  • You didn't do anything wrong, but usually, mobile phones isolate themselves from their own hotspot networks. Its behaviour may seem similar to that of a router, but it isn't actually one, and it doesn't place itself as a client of its own network (as routers do). This is to prevent attack attempts on the device from potentially unknown clients.