UDP Discovery Tutorial – Part 1

I recently had a reason to look into this so I thought I’d post a short basic example of how to use UDP to implement client/server discovery over a local network in C#.  As this is a basic example, I am not going to cover security or negotiation minutia. At least not in these short tutorials. As a note to the reader, all error handling has been omitted for the sake of clarity.

Find the Broadcast IP of your Network

A special “Broadcast Address” must be used when using UDP for the purpose of sending a datagram to all machines connected to a given network.  For example, the typical home network host/gateway of 192.168.0.1 has a broadcast address of 192.168.0.255.  If your network differs from this you can use an IPv4 broadcast address calculator like the one found here http://jodies.de/ipcalc.  We don’t want to have to figure out the broadcast IP by hand every time so we’d like to calculate it programatically.

The below example code shows one possible way of how to calculate the broadcast address for your local network adapter.  Depending on your needs, there is also a special definition for the 255.255.255.255 broadcast address which is the broadcast IP for the 0.0.0.0 network.  This special broadcast address is more limited by definition in that packets sent to it are not forwarded to the routers connecting the local network to other networks.

The below code is a fully encapsulated method to return the broadcast address of the machine that it is running on. The return is a object of the IPAddress type.

        public IPAddress calculateUdpBroadcastAddress()
        {
            //Get the local IP address of the network adapter
            IPHostEntry host;
            host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily.ToString() == "InterNetwork")
                {
                    localIP = ip;
                }
            }

            //Get the SubnetMask of the Local Network Adapter
            foreach (NetworkInterface adapter in NetworkInterface.GetAllNetworkInterfaces())
            {
                foreach (UnicastIPAddressInformation unicastIPAddressInformation in adapter.GetIPProperties().UnicastAddresses)
                {
                    if (unicastIPAddressInformation.Address.AddressFamily == AddressFamily.InterNetwork)
                    {
                        if (localIP.Equals(unicastIPAddressInformation.Address))
                        {
                            localSubnetMask = unicastIPAddressInformation.IPv4Mask;
                        }
                    }
                }
            }

            //Get the SubnetMask bytes before finding the complement
            IPAddress complimentIP = new IPAddress(localSubnetMask.Address);
            byte[] addressBytes = complimentIP.GetAddressBytes();
            byte[] complimentBytes = new byte[4];

            //Get the compliment of the SubnetMask
            for (int i = 0; i < addressBytes.Length; i++)
            {
                complimentBytes[i] = (byte)~addressBytes[i];
            }

            //bitwise OR the compliment of the Subnet Mask and the host IP
            byte[] localBytes = localIP.GetAddressBytes();
            byte[] broadcastBytes = new byte[4];
            for (int i = 0; i < localBytes.Length; i++)
            {
                broadcastBytes[i] = (byte)(complimentBytes[i] | localBytes[i]);
            }

            //Return the calculated broadcast address
            return new IPAddress(broadcastBytes);
        }

With the above code we can find the broadcast IP that we need to broadcast on to find our clients or server.

Select a Listening/Broadcasting Port

Any free port on both your client and server is acceptable for this purpose. MSDN uses port 11000 for their udp example. Personally I like utilizing ports in the 10k to 11k range for me projects as there is a fair amount of free ports in that range.

The port you’ve selected will be used in the following code example, for this example I am using port 11000.

Code to Implement the Listener

            //Update the UI and listen for a datagram until we get the right one
            bool done = false;
            while (!done)
            {
                byte[] bytes = udpListen();  //Blocking method call until a datagram is received

                //Validate the message
                string udpMessage = Encoding.ASCII.GetString(bytes, 0, bytes.Length);
                string[] udpDatagramParts = udpMessage.Split(' ');
                if (!udpDatagramParts[0].Equals("UDPBroadcasterIP:"))
                {
                    //The UDP message we received is not the right one
                    listView.Items.Add("The received datagram was incorrect ... continue listening");
                }
                else
                {
                    //The udp message is the right one
                    listView.Items.Add("Received a correct datagram ... attempting a TCP connection ... ");
                    //Save the IP for the TCP connection
                    connectionIP = udpDatagramParts[1];
                    done = true;
                }
            }

Note: The third parameter to Console.WriteLine, “Encoding.ASCII…” represents the string value sent over UDP in the datagram packet. This contains the desired negotiation information for a discovery situation, such as the IP address of the client or server you wish to connect to.

The above code is performing a blocking listen operation until a UDP datagram has been received. The UdpListen() method can be seen in its entirety in the available visual studio projects listed at the bottom of this article.

Code to Implement the Broadcaster

            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            //The sendBuf contains the message we are sending to the UDPListener, so here is where the application specific validation
            // information and the TCP connection information will be provided to the listener
            byte[] sendbuf = Encoding.ASCII.GetBytes("UDPBroadcasterIP: " + localIP.ToString());
            IPEndPoint ep = new IPEndPoint(broadcastAddress, udpPort);

            for (int i = 0; i < 100; i++)
            {
                s.SendTo(sendbuf, ep);
                Thread.Sleep(10);
            }

This is a very simple example. The broadcaster is rebroadcasting for a period of time to make sure the Listener receives it. In this example I send the datagram every 10 milliseconds for 1 second. Even after the UDP datagram is sent/received there will need to be some negotiation to ensure a more permanent connection is made between the client and server.

In Part 2 of this tutorial I will implement a TCP connection between the Broadcaster and the Listener.  Once Part 2 is published I will also update the below code projects to show the TCP connection as well.

A full implementation of this tutorial is available for download at the link below. This is still a simplified version of what you will likely need for your project but should be more complete than the above code snippets.

UDPListener.zip

UDPBroadcaster.zip

 

Blog Awakenings

Over the Christmas and New Years holiday 2015 my wife, daughter, and I were spending some time in the mountains enjoying the trees and snow.  My wife and I tend to not spend too much on Christmas gifts for each other but this year she got me something that I’ll never forget, she got me a book.

This book was special though, and I’ll never forget that Christmas.  Its safe to say this book changed my life for ever.

The book was Soft Skills, and given the snowy freezing climate I had a lot of time in doors by the fire place to get some good quality reading time in.  So I got to it and in a couple days I had managed to get through the book, as well as another I had gotten The Beer Bible, I’m not a saint!

In the remaining days of our vacation I spent a fair amount of time reading articles at simpleprogrammer.com and watching John’s videos, and then I found something, “Sign up for my free blogging course via email”.

I was iffy about it at first. I wasn’t super enthusiastic about giving out my email address to yet another web site, but everything I had read and heard about the benefits of blogging from John’s educational material changed my mind. So I signed up.

After that I started following the guide’s advice and performing the homework, and even though I have no expectation that John is actually reading my responses or actually looking at my new blog, I knew this would be a good exercise for me. This was going to help get me into a successful routine.

The first lesson or two seemed a bit slow, but they got harder, not in the amount of work that they entailed but the amount of thinking that they made me do about my goals and expectations for my own life and career.

After having made all the decisions that I needed to, at least tentatively, I finally had my blog, this blog.  I have greatly enjoyed the journey to this point and all that I have learned along the way.  The resources that John has over at simpleprogrammer.com have taught me a huge amount in my quest to become more entrepreneurial minded and I look forward to being able to put it all in to practice over time.

So if you to would like to take John’s email blogging course, you can go here to sign up.  I highly recommend that you go through the course, even if you have been blogging for a while and want to improve your blog or blogging skills.  I believe anyone can learn form the lessons in this course.

Don’t Forget to Breathe.

As first legitimate posts go, I figured this was a pretty good topic to write on since it hits so close to home for me.  In all areas of my life I am constantly having to remind myself to breathe!  It sounds like a silly thing to have to remind yourself to do but you may be more like me than you think.

You may be thinking to yourself that I sound crazy right now. You may be thinking if I, or you, had to constantly remind yourself to breathe that there would be no way anyone could live long enough for it to be an issue.  Well you’re right, so let me clarify.  You, and I, need to remind ourselves to breathe the RIGHT way! That’s right, there is a right and a wrong way to breathe!

The Wrong Way

The wrong way to breathe is the easiest, and simplest to understand because you are already doing it day in and day out!  The wrong way has three characteristics.

First, it is too fast and shallow.  Typical adult breathing fills a surprisingly small amount of your lungs with air.  Wikipedia defines the total volume of the average adult male respiratory system as 5.8 liters, and the average adult woman as 4.2 liters, that is a lot of air! The average adult inspiratory capacity is 3.5 and 2.4 liters for men and women respectively.

It makes sense that our lungs can not be fully collapsed, but even so the average person has the ability to expand and deflate their lungs by 60% of their total air capacity.   Obviously you aren’t gasping for air on each breath though, the average adult however, only breathes in 0.5 liters of air per breath and they breathe between 12 and 20 times per minute.  That means the average person is only utilizing 15-20% of their lung capacity for a given breath, but breathing much more rapidly to compensate.

The second characteristic of the wrong way to breathe is chest expansion.  When you breathe in and your chest is forced out, or more specifically you use your chest muscles to breathe in you are not expanding the lower regions of your lungs so even if you wanted to take a large breath, you will always be using less than 100% of your total lung capacity.

The third characteristic of the wrong way to breathe is weak exhalation.  When you use the wrong muscles to breathe you are not effectively expelling the old stale air from the bottom of your lungs which effectively lowers the total amount of oxygen that your lungs can absorb into your blood stream by not providing fresh air to all parts of your lungs.

The Benefits

Now that you have an idea of what “breathing wrong” entails, let me describe the benefits of the correct way of breathing just to make sure you’re a believe before you read too much further.

First it’s important to note that breathing in through your nose and out through your mouth is important.  The nose is a very important part of the breath cycle and bypassing it can contribute to many respiratory problems as described at #2 below.

There is a large fitness benefit to breathing the right way for those of us that are active.  The correct breathing cycle promotes muscle relaxation, clarity of mind, and a stronger connection between your mind and your body.  This is especially important for sports and martial arts as it promotes the necessary clarity of mind to “react without thinking”.  Now don’t think to yourself, “I don’t participate in sports or martial arts so I don’t need to bother with this crap!”, everything described so far is not only useful to people who participate in competitive physical activities, it is also extremely useful to those of us that have to sit in the same chair and think all day!

Correct breathing can allow the software developer to more effectively fight that 2pm slump by providing more air to the body to promote energy levels, can relax your body to relieve the stress of having a deadline looming over your head (#3), can give you the mental clarity to write better code, and plan out your projects more elegantly.  The benefits are practically endless.

The Right Way

So here is the technique that I use to train correct breathing habits in my day to day life.  My breathing training in the Dojo is quite different but still fundamentally based on the same principles.

Slow Abdominal Breathing Practice

From standing or sitting, while maintaining correct posture, inhale as deeply as you can through your nose, by using your abdominal muscles to expand your lungs, this inhalation should take 3 to 4 seconds, and you should see a sizable expansion in your abdomen.  Hold this breath for 1 to 2 seconds, and then exhale through the mouth for another 3 to 4 second period.  The total length of the breath should be between 7 and 10 seconds. As you practice this breathing technique more try to see if you can extend the length of each breath, this will strengthen your lungs, abdomen, and help train the feeling of deep abdominal breathing.  To start out you can perform this breathing for a few minutes a couple times a day, and try to extend your practices with time.

Fast Abdominal Breathing Practice

From standing or sitting with correct posture, inhale as deeply as you can through your nose, by using your abdominal muscles to expand your lungs. This inhalation should take 1 to 2 seconds, and you should see expansion in your abdomen. Hold this breath for .5 to 1 second, then exhale through the mouth for 1 to 2 seconds.  This whole breath should take between 2.5 and 5 seconds.

Overall Goals

These exercises are designed to help you do two things.  First, slow down your breathing, and second, transition to breathing deeply using abdominal muscles all of the time.  As you transition away from shallow chest breathing you can drop the fast Abdominal breathing practice and focus on the slower practice.  If you are an athlete or martial artist however then I’d recommend not only continuing the fast exercise but try to decrease the time it takes you to perform a fast abdominal breath.  Fast abdominal breathing skills are very beneficial for martial artists who do not wish to project their breathing when sparing, additionally in sports and martial arts when your body is being stressed to a great extent you want to be able to provide a high volume of oxygen to your muscles as quickly and efficiently as possible.  For less active people this isn’t as important.

With a slower deeper breathing cycle your lungs will be more efficiently utilized, you will be more efficiently oxygenating your blood, your muscles will be more relaxed, your mind will be more alert, and you will be less stressed through out the day.

Please comment below if this is something that you feel strongly about, or if this has helped you in your daily routine or martial arts and sports training.

Disclaimer:

Obviously there has to be a disclaimer so here goes. I am not a doctor, and this is not medical advice. If you become dizzy, woozy, or otherwise sick feeling at any point in time during the breathing exercises I described, stop the exercise immediately and consult a physician.

References:

  1. https://en.wikipedia.org/wiki/Lung_volumes#cite_note-mariebhoehn-1
  2. http://www.breathing.com/articles/nose-breathing.htm
  3. http://www.stress.org/take-a-deep-breath/
  4. http://www.mckinley.illinois.edu/units/health_ed/stress_audio/deep_breathing_txt.html

Hello World!

Hello World!

Seeing as WordPress auto-generates a first “Hello World” post for you, and given the subject of this blog I thought that creating a true “Hello World” first entry would be very appropriate.

I, as have many of you, have created many “Hello World” first applications in my day, and this post is no different. This truly is my ‘hello’ to the world of blogs and expressing my ideas in public. Like most programmers and engineers, I have always tended to prefer the solitude of my office and of my headphones to interacting with peers and colleagues.  From today forward that is no longer me.

First though, let me warn you, this blog will not be a standard technology or software development related blog, this will be a repository for my thoughts on many things, but primarily, Software Development and the Martial arts.  Sometimes the articles will involve both, and sometimes they will only touch on one of the two subjects, but they will usually involve one of the two.

I look forward to writing some(hopefully) great articles and sharing them with you all in the future.

-Aaron