如何在不使用 WIFI 管理器的情况下以编程方式获取 Android 手机在 USB Tethering 模式下连接到的 PC 的 IP 地址、默认网关和端口号?
我使用了网络接口(interface),但它没有给我正确的信息,还有其他方法吗?
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()) {
address += inetAddress.getHostAddress().toString() ;
}
}
}
最佳答案
好的,这是我所达到的解决方案,从通过网络接口(interface)接收到的地址,我删除了地址中的最后一部分,例如 192.168.1.40,我删除了 40 并从 192.168.1.0 开始循环并找出实际连接的端口。 fragment 如下
for(idx=0; idx <=255; idx++)
{
try
{
t[idx] = new Thread(new Runnable() {
public void run() {
str = IPpart + "." + idx;
socket = new Socket(str, PORT);
IP = socket.getInetAddress().toString();
Gateway = socket.getLocalAddress().toString();
}
});
t[idx].setName("IPclass");
t[idx].start();
if(IP != "")
{
closeThread();
break;
}
}catch(Exception ex){ }
}
关于android - 在没有 WIFI 的 Android 中以编程方式在 USB Tethering 模式下的 PC 的 IP 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6289714/