2012-08-12 89 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] 
相關問題