format Ip Address - Android Network

Android examples for Network:IP Address

Description

format Ip Address

Demo Code


import java.math.BigInteger;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.ByteOrder;

public class Main {

  public static String formatIpAddress(int ipAdress) {
    // Convert little-endian to big-endianif needed
    if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) {
      ipAdress = Integer.reverseBytes(ipAdress);
    }//from w  w w  .j  a  v  a 2s  .  com

    byte[] ipByteArray = BigInteger.valueOf(ipAdress).toByteArray();

    String ipAddressString;
    try {
      ipAddressString = InetAddress.getByAddress(ipByteArray).getHostAddress();
    } catch (UnknownHostException ex) {
      ipAddressString = null;
    }
    return ipAddressString;
  }
}

Related Tutorials