Outputs a formatted (###.###.###.###) IP Address string - CSharp System.Net

CSharp examples for System.Net:IP Address

Description

Outputs a formatted (###.###.###.###) IP Address string

Demo Code

//  Licensed under the Apache License, Version 2.0 (the "License");
using System.Collections;
using System.Text;
using System;//from   ww  w .j a  va2 s .  c o m

public class Main{
    /// <summary>
      /// Outputs a formatted (###.###.###.###) IP Address string
      /// </summary>
      /// <param name="offset">Start index</param>
      /// <returns>Formatted IP address string</returns>
      public static string ToIPAddress(this byte[] array, int offset)
      {
         if (array == null || array.Length == 0 || offset < 0 || offset >= array.Length)
            return String.Empty;

         string[] ipAddr = new string[4];

         ipAddr[0] = array[offset + 0].ToString();
         ipAddr[1] = array[offset + 1].ToString();
         ipAddr[2] = array[offset + 2].ToString();
         ipAddr[3] = array[offset + 3].ToString();

         return String.Concat(ipAddr[0], ".", ipAddr[1], ".", ipAddr[2], ".", ipAddr[3]);
      }
        /// <summary>
      /// Outputs a UTF8 string converted from a subset of bytes in this array.
      /// </summary>
      /// <param name="offset">Start index</param>
      /// <param name="length">Number of bytes to convert.</param>
      /// <returns>A string converted from bytes in this array.</returns>
      public static string ToString(this byte[] array, int offset, int length)
      {
         if (array == null || array.Length == 0 || array.Length < (offset + length))
            return String.Empty;

         return new string(Encoding.UTF8.GetChars(array, offset, length));
      }
      /// <summary>
      /// Outputs a UTF8 string converted from all bytes in this array.
      /// </summary>
      /// <param name="offset">Start index</param>
      /// <param name="length">Number of bytes to process</param>
      /// <returns>A string converted from all bytes in this array.</returns>
      public static string ToString(this byte[] array)
      {
         if (array == null || array.Length == 0)
            return String.Empty;

         return new string(Encoding.UTF8.GetChars(array));
      }
}

Related Tutorials