The art of Windows Phone

Menu

Simple network discovery to find Netduinos from Windows

With the advent of Internet-of-Things things, you’ll probably need a decent way to actually find all of the things on your network.

Fun fact: If you send a UDP packet to *.255 on your network, your router will then send that along to all the devices on your network. So if your local network is on 192.168.1.x, then send it to 192.168.1.255. Or if you want to send it to everything, then you can send to 255.255.255.255.

In my case, I’ve got this awesome little guy…

…setup with DHCP, so the IP occasionally changes. I’ve got a Windows 10 app that needs to connect to it, so we can use the way above to find the Netduino on the network.

varbuffer=newbyte[4];// We're only ever looking for "ping" so 4 bytes is enough

while(true)

{

Thread.Sleep(10);

if(!_socket.Poll(-1,SelectMode.SelectRead))continue;

EndPoint remote=newIPEndPoint(IPAddress.Any,_port);

varreceivedByteCount=_socket.ReceiveFrom(buffer,refremote);

if(receivedByteCount>0)

{

varreceived=BytesToString(buffer).ToLower();

if(received=="ping")

_socket.SendTo(Encoding.UTF8.GetBytes("pong"),remote);

}

}

}

publicstaticstringBytesToString(byte[]bytes)

{

varchars=newchar[bytes.Length];

for(varc=0;c<bytes.Length;++c)

chars[c]=(char)bytes[c];

returnnewstring(chars);

}

}

}

It is pretty simple stuff. We setup a UDP server, then constantly loop looking if we’ve received anything. If we receive “ping”, then send “pong” back to whatever sent it.

Side note: Initially I was checking the _socket.Available value to see if there is new data, then run _socket.ReceiveFrom. That had a weird behavior where it would see there were x bytes available, but then lock on the _socket.ReceiveFrom line until the next message you sent.
I contacted Chris Walker/Mr.Netduino and he found out the issue was that internally _socket.Available actually pulls the data into an internal buffer to give you a number of bytes, but that means that on the next line _socket.ReceiveFrom has no data left to read (it is all in the buffer, which only _socket.Receive uses). He’s filed this GHI discussing the issue. The simple workaround is to not check available bytes, but rather just see if the value returned from _socket.ReceiveFrom is > 0.

Then initialize it in the main method:

C#

1

2

3

4

5

6

7

8

9

10

11

12

13

publicclassProgram

{

publicstaticvoidMain()

{

varudpServer=newUDPNetworkDiscoveryServer(80);

udpServer.StartServer();

while(true)

{

Thread.Sleep(10);

}

}

}

Universal Windows app bit

On the Windows app side, we have a super basic UI – literally just to check that the code is working. Please don’t ever publish something that looks like this.