Home > Tutorial > Java InetAddress Hex String to Octet String

Java InetAddress Hex String to Octet String

If your doing a snmpwalk or snmpget to retrieve a single MIB or MIB Table from a device, there’s a good chance one of the table values will be a Java InetAddress in the form of a hex string.

What is an ipv4 address? An ipv4 address is made up of 4 octets between 0-255 with dots between them. For example, this is a valid ipv4 ipaddress 127.0.0.1, sometimes referred to as the loopback address.

If your doing an snmpget or snmpwalk that will return an ipv4 ipaddress, it will be returned as a hex string. This tutorial shows you how to take a hex string and convert it to a readable ipv4 address.

This tutorial import the snmp4j libraries and uses the following import classes in order to convert the hex string ipaddress to octet string ipaddress.

  • import org.snmp4j.smi.Address;
  • import org.snmp4j.smi.IpAddress;
  • import org.snmp4j.smi.OctetString;


Java Hex String to Octet String

The snmp4j library will return ip addresses as hex strings. In our example, the ipv4 ipaddress 127.0.0.1 will be returned by snmp4j as 7f:00:00:01, which will need to be converted an octet string.

package com.jcd.java.tutorials.MavenProject;


import org.snmp4j.smi.Address;
import org.snmp4j.smi.IpAddress;
import org.snmp4j.smi.OctetString;

public class JavaInetAddress {

	public static void main(String[] args) 
	{
		String hexIpString = "7f:00:00:01";
		
		try {
            OctetString octetString = OctetString.fromHexString(hexIpString);
            Address snmpAddr = new IpAddress(octetString.getValue());
            String ipAddress = snmpAddr.toString();
            System.out.println("ipaddress="+ipAddress);
		}
		catch(Exception e) {
			System.out.println("RemoteAddr Exception");
		}

	}
}


Java Hex String to Octet String Output

ipv4 address: 127.0.0.1



Concluding Comments

If your doing any type of MIB retrieval in your Java application that may return an ipaddress, you will need to know how to convert the hex string to an octet string. This tutorial is using the snmp4j libraries that i have included as a dependency in my pom.xml file.

<dependency>
   <groupId>org.snmp4j</groupId>
   <artifactId>snmp4j</artifactId>
   <version>2.0.0</version>
</dependency>



Java References:

Smedley
Posted by

Smedley

Smedley has been programming in Java for about twenty years. He enjoys sharing code samples to other fellow Java coders.

You may also like...

(1) Comment

  1. martin

    been looking for a solution

Leave a Reply

Your email address will not be published. Required fields are marked *

Copyright © 2018 JavaCodeDepot