Skip to content

Instantly share code, notes, and snippets.

@massenz
Last active December 7, 2021 15:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save massenz/6908046 to your computer and use it in GitHub Desktop.
Save massenz/6908046 to your computer and use it in GitHub Desktop.
How to convert from JSON to Inet4Address in Java - incidentally, this is the only way to create an InetAddress object for a host that is not DNS-resolvable (see in the example, how it sets both hostname and IP for an arbitrary server).
package com.alertavert.samples;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.Inet4Address;
/**
* Simple example to show how to create a Java @link{InetAddress} from a JSON representation.
*
* <p>Jackson will try to use the @link{Inet4Address#Inet4Address(String, int)} constructor, and it
* will fail if the JSON tries to pass instead an array of four bytes; in other words this
* <strong>will fail</strong>:
*
* <pre>{
* "hostName": "mordor",
* "address": [192, 168, 1, 50]
* }</pre>
*
* <p>The four octets must instead be first converted to a four-byte @code{int} and then passed
* in like thus:
*
* <pre>{
* "hostName": "mordor",
* "address": -1062731470
* }</pre>
*
* @author marco
*
*/
public class JsonSerialize {
static int fromByteArray(int[] ipv4) {
int result = 0;
for (int i = 0; i < 4; ++i) {
result += (ipv4[i] & 0xFF) << (8 * (3 - i));
}
return result;
}
static String ipToString(byte[] ip) {
StringBuilder sb = new StringBuilder();
for (byte b : ip) {
sb.append(b & 0xFF).append('.');
}
sb.setLength(sb.length() - 1);
return sb.toString();
}
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
int address = fromByteArray(new int[]{192, 168, 1, 50});
System.out.println("The address is: " + address);
String json = "{\"hostName\": \"mordor\", \"address\": " + address + "}";
try {
Inet4Address ip = mapper.readValue(json, Inet4Address.class);
System.out.println("Host: " + ip.getHostName());
System.out.print("IP: " + ipToString(ip.getAddress()));
} catch (Exception e) {
System.err.println("The JSON could not be converted: " + e.getLocalizedMessage());
System.exit(1);
}
}
}
@michaelthecsguy
Copy link

Nice... it looks like this is for IP4 only?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment