I want to send a UDP packet from a phone to the limited broadcast address (IPAddress.Broadcast = 255.255.255.255).
This is what I have so far, and it works in a Windows app:
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
byte[] data = Encoding.UTF8.GetBytes("test data");
SocketAsyncEventArgs a = new SocketAsyncEventArgs();
a.RemoteEndPoint = new IPEndPoint(IPAddress.Broadcast, 11000);
a.SetBuffer(data, 0, data.Length);
a.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
{
Console.WriteLine(e.SocketError);
});
socket.SendToAsync(a);
The SetSocketOption call is required in order to prevent an "access denied" exception. Unfortunately that method doesn't seem to be available on WP7. The UDP sample code given on the App Hub community site is using multicast to achieve similar results, but the device I'm trying to contact isn't able to deal with multicast.
Is there any way to do this sort of broadcast on Mango?
You can use
socket.ConnectAsync(a);
.From Documentation:
Optionally, a buffer may be provided which will atomically be sent on the socket after the ConnectAsync method succeeds. (UDP is a connectionless protocol, should send always when network works)