【问题标题】:get the internet ip address获取互联网 IP 地址
【发布时间】:2012-08-12 22:20:15
【问题描述】:

我需要获取互联网 IP 地址。现在我想使用 linux 终端来获取它,所以我输入“ifconfig”。我的 android 手机通过 thetering 连接,我注意到“ifconfig”的输出中没有我的互联网 IP 地址。

usb0      Link encap:Ethernet  HWaddr 6a:22:38:4d:92:36  
          indirizzo inet:192.168.42.79  Bcast:192.168.42.255  Maschera:255.255.255.0
          indirizzo inet6: fe80::6822:38ff:fe4d:9236/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:31359 errors:4 dropped:0 overruns:0 frame:4
          TX packets:27688 errors:0 dropped:0 overruns:0 carrier:0
          collisioni:0 txqueuelen:1000 
          Byte RX:30033107 (30.0 MB)  Byte TX:4855114 (4.8 MB)

这是“ifconfig”命令的输出。 有没有一种通用的方法来获取 IP 地址,通过脚本命令或“c”函数?

【问题讨论】:

    标签: android linux ip


    【解决方案1】:

    这是一个可能有帮助的 Java sn-p:

    WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    int ipAddress = wifiInfo.getIpAddress();
    

    【讨论】:

      【解决方案2】:

      以下是通过Java代码获取IP地址的代码(无论是通过3G还是WIFI连接)

      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(LOG_TAG, ex.toString());
          }
          return null;
      }
      

      参考:Get the ip address of your device

      如果你想在 C 中获取 IP 地址,这个帖子可能会有所帮助:

      using C code to get same info as ifconfig

      【讨论】:

      • 嗨 Chandra,我可以获取互联网 IP 地址,而不是设备 IP。如果手机连接到 wifi 或 3g 或 2g 或无论如何。手机有上网方式,请需要那个互联网IP地址..
      【解决方案3】:

      你的问题有点含糊。您在寻找什么样的 IP 地址?如果您正在寻找您的 LAN IP,ifconfigiwconfig 就足够了。如果您正在寻找 WAN IP,请使用

      wget -qO- http://cmyip.com | grep "My IP Address Is"
      你应该可以看到你的IP。我不知道你使用的安卓终端是否支持wget,但值得一试。

      【讨论】:

        【解决方案4】:

        “inet:”之后的 IP 地址,即 192.168.42.79 是您的 IP 地址。但是,话虽这么说,最短的 python 脚本是......

        #!/usr/bin/python
        
        import socket
        
        s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('google.com',80))
        return s.getsockname()[0]
        

        【讨论】:

          猜你喜欢
          • 2018-10-11
          • 2012-02-04
          • 2018-12-01
          • 1970-01-01
          • 1970-01-01
          • 2011-06-01
          • 2013-06-27
          • 2011-11-12
          • 2014-05-28
          相关资源
          最近更新 更多