Java program to convert Byte array to IP Address


Given with a Byte array ad the task is to convert it into an IP address using the IPAddress class in java and display the result.

What is a Byte Array

A byte comprises of 8 bits and byte array comprises of contiguous bytes which stores the binary information. In java, byte is a primitive datatype that can be understood as the byte of computer i.e. it is of 8 bits and it can hold values ranging for -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 IPAddress Class

In java, 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[])

Example

Input-: 171, 32, 101, 11
Output-: 171.32.101.11
Input-: 172, 31, 102, 14
Output-: 172.31.102.14

Approach we are using in the below program is as follows

  • 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 function ToString() to convert the Address into string representation
  • Print the result

ALGORITHM

START
Step 1-> declare class convert for conversion
   public class convert
   call class public static void Main()
      set IPAddress add = new IPAddress(new byte[]  { 171, 32, 101, 11 })
         call Console.WriteLine(add.ToString())
         End
   End
STOP

Example

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

Updated on: 20-Nov-2019

662 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements