[Android] Android 學習筆記:取得手機目前所有可用的網路介面與 IP
最近有個程式需求,要顯示手機上所有的 IP address~
這東西可以用 NetworkInterface 和 InetAddress 來取得~
下面的程式可以將所有的網路介面和其關聯的 IP address 都顯示出來:
public String getPhoneIPAddrs()
{
String sAddr = “”;
try
{
for (Enumeration<NetworkInterface> enumInterfaces = NetworkInterface.getNetworkInterfaces(); enumInterfaces.hasMoreElements(); )
{
// Get next network interface
NetworkInterface interface = enumInterfaces.nextElement();
for (Enumeration<InetAddress> enumIPAddrs = interface.getInetAddresses(); enumIPAddrs.hasMoreElements(); )
{
// Get next IP address of this interface
InetAddress inetAddr = enumIPAddrs.nextElement();
// Exclude loopback address
if (!inetAddr.isLoopbackAddress())
{
if (sAddr != “”)
{
sAddr += “, “;
}
sAddr += “(“ + interface.getDisplayName() + “) “ + inetAddr.getHostAddress().toString();
}
}
}
}
catch (SocketException e)
{
e.printStackTrace();
}
return sAddr;
}
{
String sAddr = “”;
try
{
for (Enumeration<NetworkInterface> enumInterfaces = NetworkInterface.getNetworkInterfaces(); enumInterfaces.hasMoreElements(); )
{
// Get next network interface
NetworkInterface interface = enumInterfaces.nextElement();
for (Enumeration<InetAddress> enumIPAddrs = interface.getInetAddresses(); enumIPAddrs.hasMoreElements(); )
{
// Get next IP address of this interface
InetAddress inetAddr = enumIPAddrs.nextElement();
// Exclude loopback address
if (!inetAddr.isLoopbackAddress())
{
if (sAddr != “”)
{
sAddr += “, “;
}
sAddr += “(“ + interface.getDisplayName() + “) “ + inetAddr.getHostAddress().toString();
}
}
}
}
catch (SocketException e)
{
e.printStackTrace();
}
return sAddr;
}
執行後的結果字串,是類似下面的樣子:
(eth0) 10.1.117.200, (ppp1) 192.168.252.1
(本頁面已被瀏覽過 205 次)