Friday 9 October 2015

Java Get Raw IP address

"public byte[] getAddress()" method of InetAddress class, returns the raw IP address of this InetAddress object.
import java.net.InetAddress;

public class Main {
  public static void main(String args[]) {
    InetAddress address = InetAddressUtil.getLocalHost();
    byte[] addr = address.getAddress();
    
    for(byte temp : addr){
      /*
       * The bytes returned by getAddress() are unsigned, java don't have unsigned numbers
       * Following logic promote bytes to int.
       */
      int unsignedByte = temp < 0 ? temp + 256 : temp;
      System.out.print(unsignedByte+ ":");
    }
  }
}



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment