Getting your Machines IP Address

I was working on some code recently where I needed to get the IP Address of the current machine that the code was executing on. I settled on this snippet below. I thought I would share it.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;

namespace Utility
{
    public sealed class MachineIPAddress
    {
        private MachineIPAddress() { }

        public static string RetrieveIPAddress
        {
            get
            {
                var hostEntry = Dns.GetHostEntry(Dns.GetHostName());
                var ip = (from addr in hostEntry.AddressList
                          where String.Compare(addr.AddressFamily.ToString(), "InterNetwork", StringComparison.OrdinalIgnoreCase) == 0
                          select addr.ToString()
                    ).FirstOrDefault();

                return ip;
            }
        }
    }
}
Participate with Coding in the Trenches on Facebook

Participate with Coding in the Trenches on Facebook by Click the button above.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s