Objects in this mirror are closer to Microsoft Technologies. DNM objective is to help users on Microsoft technologies by providing Articles, snippets, Interview Questions.

03 September 2012

convert IP address to binary format using IPAddress Class in C#


In this snippet we will see how to convert an IP address to binary format using System.Net.IPAddress class.

static List<string> ConvertIPAddressToBinary(string input)
        {
           IEnumerable<string> binaries= IPAddress.Parse(input).GetAddressBytes().Select( x=> Convert.ToString(Convert.ToInt32(x), 2).PadLeft(8, '0'));
           return binaries.ToList();
        }
 
  static void Main()
        {
            List<string> listBinaries = ConvertIPAddressToBinary(“192.168.0.1”)
            foreach (string binary in listBinaries)
            {
                Console.Write(binary + " ");
            }
        }
Output : 11000000 10101000 00000000 00000001

IPAddress class contains the address of a computer on an IP network and supports IPv4 or IPv6.

0 Comments:

Post a Comment