【问题标题】:Can I get the IP address of the access point to I am connected to over wifi?我可以获取通过 wifi 连接的接入点的 IP 地址吗?
【发布时间】:2013-07-22 22:55:00
【问题描述】:

您好,我是 android 编程新手。我基本上是在尝试连接到接入点并向其发送命令。通过 wifi 连接到它后,是否可以通过编程方式获取它的 IP 地址,以便我可以与它建立 http 连接? 目前我知道我们可以获取设备IP,但不确定是否可以获取接入点IP。请帮忙。提前致谢。

【问题讨论】:

  • 从那个副本中并不清楚你所问的是否有意义。
  • @kabuko 我指的接入点确实分配了一个 IP 地址。我可以ping通并连接到它。我的问题是是否可以从 android 应用程序中获取此 IP。此外,重复的帖子没有回答这个问题。

标签: android networking wifi


【解决方案1】:
public static String getApIpAddr(Context context) {
    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    DhcpInfo dhcpInfo = wifiManager.getDhcpInfo();
    byte[] ipAddress = convert2Bytes(dhcpInfo.serverAddress);
    try {
        String apIpAddr = InetAddress.getByAddress(ipAddress).getHostAddress();
        return apIpAddr;
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
    return null;
}

private static byte[] convert2Bytes(int hostAddress) {
    byte[] addressBytes = { (byte)(0xff & hostAddress),
            (byte)(0xff & (hostAddress >> 8)),
            (byte)(0xff & (hostAddress >> 16)),
            (byte)(0xff & (hostAddress >> 24)) };
    return addressBytes;
}

【讨论】:

    【解决方案2】:

    我假设您的意思是设备连接到的接入点的外部(公共)IP 地址。如果是这样,是的,有一种简单的方法可以获取设备连接到的接入点的公共 IP 地址。只需在 Web 服务器上设置一个脚本,该脚本将回显连接到它的任何客户端的 IP 地址(类似于 www.whatismyip.com)。然后,您的设备只需向脚本发出 GET 请求,这将返回设备所连接的接入点的外部 IP。

    【讨论】:

    • 谢谢,但很遗憾,我无法访问任何其他 Web 服务器。这需要是一个独立的 android 应用程序,它只与它所连接的接入点交互。另外,接入点的 IP 是指由 DHCP 代理分配给它的 IP,使用它可以 ping 接入点。
    【解决方案3】:

    我正在使用它来获取 IP 地址

    try {
               for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) 
                   {
                        NetworkInterface intf = en.nextElement();       
                        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();enumIpAddr.hasMoreElements();) 
                          {
                            InetAddress inetAddress = enumIpAddr.nextElement();
                            if (!inetAddress.isLoopbackAddress())
                             { 
                             //My IP address
                                   String Ip= inetAddress.getHostAddress().toString();
    
                             }   
                           }
                      }
    
                }
         catch (SocketException e) 
         { 
           Log.e("Error occurred  ", e.toString());
          }
    

    【讨论】:

    • 这是完美的代码,但我认为它不适用于 wifi
    • 谢谢高拉夫。上面的代码在连接wifi时返回一个ipv6地址。所以我无法检查这是否是正确的地址。我也尝试过包含 if (!inetAddress.isLoopbackAddress() && (inetAddress instanceof Inet4Address)),但我还是没有得到任何 IPv4 地址。我连接的 AP 确实有一个 IPv4 地址,我可以从子网内 ping 它。但这并没有返回相同的结果。
    猜你喜欢
    • 1970-01-01
    • 2019-10-10
    • 1970-01-01
    • 1970-01-01
    • 2020-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多