【问题标题】:Get the IPaddress of the computer in an Android project using java使用java获取Android项目中电脑的IP地址
【发布时间】:2011-07-15 13:06:07
【问题描述】:

我正在使用ksoap2-android,我需要使用 java 获取 IP 地址,这样我就不必每次都手动输入。

我所说的 IP 地址是指,例如,如果我使用命令 shell 执行 ipconfig
连接特定的 DNS 后缀。 :
链接本地 IPv6 地址 。 . . . . : f0::ed2:e3bf:8206:44%13
IPv4 地址。 . . . . . . . . . . : 192.168.1.107
子网掩码 。 . . . . . . . . . . : 255.255.255.0
默认网关 。 . . . . . . . . : 192.168.1.1

问题是正在开发一个安卓应用,而模拟器的 IP 类型与机器的不同。
我需要获取机器的IP,怎么做?

非常感谢

【问题讨论】:

    标签: java android ip-address ip android-ksoap2


    【解决方案1】:

    试试这个链接

    http://www.droidnova.com/get-the-ip-address-of-your-device,304.html

    你也可以试试这个命令adb shell netcfg

    【讨论】:

      【解决方案2】:
      public String getLocalIpAddress() {
              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()) {
                              return inetAddress.getHostAddress().toString();
                          }
                      }
                  }
              } catch (SocketException ex) {
                  Log.e(tag, ex.toString());
              }
              return "";
          }
      

      【讨论】:

      • 虽然这确实有效,但我得到了一些误报,我必须使用正则表达式验证 IP 地址格式,这似乎适用于我的所有用例。
      • 我试过了,我在网上发现了同样的方法,但我不相信这行得通。只有一个网络连接(不在 wi-fi 上),我有两个接口。一个是loopback,另一个是rmnet0,我看过的是网络接口。使用此代码,我将 rmnet0 作为我的本地 IP。但是,当我设置一个网页以根据请求标头从浏览器访问时吐出我的 IP 时,IP 有很大的不同,如果我点击任何“我的 ip 是什么”网站,IP 是相同的浏览器也是如此。有什么想法吗?
      【解决方案3】:
      InetAddress iA=InetAddress.getLocalHost();
      System.out.println(iA.getHostAddress());
      

      另见

      【讨论】:

      • 嘿,这个客户端连接@JigarJoshi的服务器的IP地址呢?
      【解决方案4】:

      要获取您的 android 设备的 IP 地址,请使用此代码。

      WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
      WifiInfo wifiInfo = wifiManager.getConnectionInfo();
      int ipAddress = wifiInfo.getIpAddress();
      String ip = intToIp(ipAddress);
      
      public String intToIp(int i) {
      
         return ((i >> 24 ) & 0xFF ) + "." +
                     ((i >> 16 ) & 0xFF) + "." +
                     ((i >> 8 ) & 0xFF) + "." +
                     ( i & 0xFF) ;
      }
      

      【讨论】:

      • 如果他们没有启用 WiFi,只有 3G 怎么办?
      • @Matt 我不知道,但 3G 连接不提供 IP 地址吗?
      • 是的,他们有,我只是想知道这段代码是否还能工作,仅此而已。 :)
      • 嘿,这段代码对我有用....但是返回的字符串顺序不正确
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-26
      • 1970-01-01
      • 1970-01-01
      • 2013-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多