Convert Byte Array to IP Address in Java
In this article, we will learn to convert a byte array into an IP address using the IPAddress class in Java. This program takes a series of bytes, representing an IP address in binary form, and converts them into a standard dot-separated string representation of an IP address. We'll go through the simple steps of declaring a byte array and then converting it into a readable IP address format.
What is a Byte Array?
A byte comprises 8 bits and a byte array comprises contiguous bytes which store the binary information. In Java, a byte is a primitive datatype that can be understood as the byte of a computer i.e. it is of 8 bits and can hold values ranging from -128 to 127.
Declaring a byte ? byte name_of_byte_variable = initializer;
Declaring a byte array ? byte[] name_of_byte_array = new byte[];
What is an IP address class?
In Java, the IPAddress class is used to get the IP address of any system. It is present in the System.net class which needs to be imported to make use of IPAddress class.
Syntax
IPAddress ObjectName = new IPAddress(byte[])
Problem Statement
Given a Byte array, the task is to convert it into an IP address using the IPAddress class in Java and display the result.
Input 1
171, 32, 101, 11
Output 1
171.32.101.11
Input 2
172, 31, 102, 14
Output 2
172.31.102.14
Steps to convert Byte array to IP Address
Following are the steps to convert the Byte array to an IP Address
- Import the class System.net.
- Input the numbers as the bytes in the byte array
- Create the object of class IPAddress and pass the byte array to its object
- Use the function ToString() to convert the Address into a string representation
- Print the result.
Java program to convert Byte array to IP Address
Below is the Java program to convert a Byte array to an IP Address
using System; using System.Net; public class convert { public static void Main() { IPAddress add = new IPAddress(new byte[] { 171, 32, 101, 11 }); Console.WriteLine(add.ToString()); } }
Output
171.32.101.11
Code Explanation
The program starts by importing the necessary classes. We create a byte[] array that holds the bytes representing the IP address. Then, we create an instance of the IPAddress class, passing the byte array to its constructor. The ToString() method is used to convert the IP address into its readable format, and the result is displayed using Console.WriteLine(). The result is a dot-separated IP address like "171.32.101.11."