2012-08-12 152 views
-1

我需要得到互联网ip地址。现在我想使用linux终端来获取它,所以我输入“ifconfig”。我通过我的android手机通过thetering连接,并且我注意到在“ifconfig”的输出中没有我的Internet IP地址。得到互联网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”功能?

回答

1

下面是一个Java代码,这可能有助于:

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

下面的代码是通过Java代码(无论其通过3G或WIFI连接)来获得IP地址

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

+0

嗨钱德拉,我可以得到互联网ip地址,而不是设备ip。如果手机连接到无线或3G或2G或无论如何。移动互联网手段,需要互联网IP地址.. – harikrishnan 2013-09-20 13:27:16

0

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

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

0

“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]