Search code examples
delphidelphi-11-alexandria

How to convert integer value of ip address to standard IP address


Pls. can you help me how to convert integer value of ip address to standard ip address?

A got integer value from

tmpWifiServiceNative:= TAndroidHelper.Activity.getSystemService(TJContext.JavaClass.WIFI_SERVICE);

tmpWifiManager:= TJWifiManager.Wrap((tmpWifiServiceNative as ILocalObject).GetObjectID);

tmpWifiIPAddress:= tmpWifiManager.getDhcpInfo.ipAddress //This returns integer value

Solution

  • Simply use this function:

    uses
      Androidapi.Helpers,
      Androidapi.JNIBridge,
      Androidapi.JNI.Java.Net,
      Androidapi.JNI.JavaTypes;
      
    
    function ConvertIntegerIPAddressToString(AIntegerIPAddress: Integer): string;
    var
      IPAddress: Integer;
      SystemByte: TJavaArray<Byte>;
      InetAddress: JInetAddress;
    begin
      if (TJByteOrder.JavaClass.nativeOrder.equals(TJByteOrder.JavaClass._GetLITTLE_ENDIAN)) then
        IPAddress:= TJInteger.JavaClass.reverseBytes(AIntegerIPAddress)
      else
        IPAddress:= AIntegerIPAddress;
        
      SystemByte:= TJBigInteger.JavaClass.valueOf(IPAddress).toByteArray;
        
      try
        InetAddress:= TJInetAddress.JavaClass.getByAddress(SystemByte);
        
        Result:= JStringToString(InetAddress.getHostAddress);
      except
        Result:= 'Convert error';
      end;
    end;