Program to convert Byte array to IP Address

Given a Byte Array, convert it to the format of IP Address.

Examples:

Input : {16, 16, 16, 16}
Output : 16.16.16.16

Input : {172, 31, 102, 14}
Output : 172.31.102.14

Byte arrays:
A byte is collection of bits (8). Byte arrays are arrays of contiguous bytes and can be used to store binary information. With byte arrays, one can work directly on bytes and thus control the bits. Byte arrays provide a faster way of accessing each byte in use.
For more details: https://msdn.microsoft.com/en-us/library/dd126860.aspx



Syntax:

byte[] ArrayName = new byte[] 

IPAddress Class:
The IPAddress class contains the address of computer on IP network. IPAddress class accommodates IP Address values passed to or returned by Simple Network Management Protocol (SNMP) agents by extending the OctetString Class. IPAddress Class comes under ‘System.Net’ namespace.

Refer Link for details: http://snmpsharpnet.sourceforge.net/ver0-4/html/T_SnmpSharpNet_IpAddress.htm

Syntax:

[Serializable]
public class IPAddress

Using Byte Arrays with IPAddress Class

IPAddress ObjectName = new IPAddress(byte[])

Approach:
The IPAddress Class is used to get the IP address. The IP Address is created with the Address property set to address. If the length of address is 4, IPAddress(Byte[]) constructs an IPv4 address otherwise, an IPv6 address with a scope of 0 is constructed. The Byte array is assumed to be in network byte order with the most significant byte in index position 0.

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# code to convert Byte array to IP Address
using System;
using System.Net;
  
public class GFG {
  
    public static void Main()
    {
  
        /* Initializes a new instance of the 
        IPAddress class with the address 
        specified as a Byte Array.*/
        IPAddress add = new IPAddress(new byte[] 
                            { 172, 31, 102, 14 });
  
        /* ToString() Converts an Internet address
        to its standard notation and 
        console.WriteLine is used for printing*/
        Console.WriteLine(add.ToString());
    }
}

chevron_right


Output:

172.31.102.14


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.