• Two Ways in Delphi to Get IP Address on Android


    1. Via NDK

    Refer Delphi Call getifaddrs and freeifaddrs on Android

    uses Posix.Ifaddrs, Posix.SysSocket, Posix.ArpaInet, Posix.NetinetIn;
    
    var
      FPifaddrs: Pifaddrs;
      FPin_addr: Pointer;
      Fsa_family: sa_family_t;
      FPtrWrapper: TPtrWrapper;
    begin
      getifaddrs(FPifaddrs);
      FPtrWrapper := TMarshal.AllocMem(INET6_ADDRSTRLEN);
      while FPifaddrs <> Nil do
      begin
        Fsa_family := FPifaddrs.ifa_addr.sa_family;
        if (Fsa_family = AF_INET) or (Fsa_family = AF_INET6) then
        begin
          if Fsa_family = AF_INET then
            FPin_addr := @Psockaddr_in(FPifaddrs.ifa_addr).sin_addr
          else
            FPin_addr := @Psockaddr_in6(FPifaddrs.ifa_addr).sin6_addr;
          inet_ntop(Fsa_family, FPin_addr, FPtrWrapper.ToPointer, INET6_ADDRSTRLEN);
          Writeln(TMarshal.ReadStringAsAnsi(FPtrWrapper));
        end;
        FPifaddrs := FPifaddrs.ifa_next;
      end;
      TMarshal.FreeMem(FPtrWrapper);
    end;

    2. Via JNI

    uses Androidapi.JNI.Net, Androidapi.JNI.Java.Net, Androidapi.JNI.JavaTypes,
      Androidapi.Helpers;
    
    var
      FJEnumOfNet: JEnumeration;
      FJNet: JNetworkInterface;
      FJEnumOfAddr: JEnumeration;
      FJAddr: JInetAddress;
    begin
      FJEnumOfNet := TJNetworkInterface.JavaClass.getNetworkInterfaces;
      while FJEnumOfNet.hasMoreElements do
      begin
        FJNet := TJNetworkInterface.Wrap(FJEnumOfNet.nextElement);
        FJEnumOfAddr := FJNet.getInetAddresses;
        while FJEnumOfAddr.hasMoreElements do
        begin
          FJAddr := TJInetAddress.Wrap(FJEnumOfAddr.nextElement);
          Writeln(JStringToString(FJAddr.getHostAddress.toString));
        end;
      end;
    end;
  • 相关阅读:
    2021 CCPC 桂林站 补题
    2021 ICPC 上海 流水账
    2021 ICPC 沈阳 补题
    vi中的多行注释和取消注释
    查询列表可筛选可模糊查询的写法
    mybatisplus逻辑删除deleted
    @JsonFormat
    @Component类相互引用的加载顺序
    Chrome浏览器嗅探方法
    DataAdapter.FillSchema 方法
  • 原文地址:https://www.cnblogs.com/JebediahKerman/p/Two_Ways_in_Delphi_to_Get_IP_Address_on_Android.html
Copyright © 2020-2023  润新知