gpt4 book ai didi

android - 如何在 android 设备中找到以太网连接的子网掩码、网关、DNS 值?

转载 作者:太空狗 更新时间:2023-10-29 14:40:46 25 4
gpt4 key购买 nike

我有android PC device , handheld device它们通过以太网连接。现在我能够获取设备的 IP 地址和 mac 地址,但我还需要获取子网掩码、网关、pri-sec DNS 值。请任何人告诉我如何以编程方式找到这些值。

查找IP地址和mac地址的代码是-

  connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
networkInfo = connectivityManager.getActiveNetworkInfo();
networkType = networkInfo != null ? networkInfo.getTypeName() : "";
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()) {
ipAddress = inetAddress.getHostAddress().toString();
System.out.println("ipaddress=" + ipAddress + " formatter ip" + Formatter.formatIpAddress(inetAddress.hashCode()));
}
}
}
} catch (SocketException ex) {

}

try {
String interfaceName = "wlan0";
if (networkType.equals("ETHERNET")) {
interfaceName = "eth0";
}
List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces) {
if (!intf.getName().equalsIgnoreCase(interfaceName)) {
continue;
}
byte[] mac = intf.getHardwareAddress();
if (mac == null) {
continue;
}
StringBuilder buf = new StringBuilder();
for (byte aMac : mac) {
buf.append(String.format("%02X:", aMac));
}
if (buf.length() > 0) {
buf.deleteCharAt(buf.length() - 1);
}
macaddress = buf.toString();
}
} catch (Exception ex) {
ex.printStackTrace();
}

以下 2 个问题可能与您无关,但我已经记住了,所以请任何人解释一下,我将不胜感激。

1) 如果我同时拥有 WIFI 和以太网连接,那么我如何确定我的应用程序是从哪个连接连接到服务器的。(除了我使用的网络类型代码)?

2) 是否有可能在设备中同时连接 WiFi 和以太网,并且我可以从这两种网络类型中获取 mac 地址、ip 地址和所有其他值?

最佳答案

private static String intToIP(int ipAddress) {
String ret = String.format("%d.%d.%d.%d", (ipAddress & 0xff),
(ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff),
(ipAddress >> 24 & 0xff));
return ret;
}

public String GetSubnetMask_WIFI() {
// wifii= (WifiManager)
getCurrentActivity().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();

DhcpInfo dhcp = wifiManager.getDhcpInfo();
String mask = intToIP(dhcp.netmask);

return mask;
}

关于android - 如何在 android 设备中找到以太网连接的子网掩码、网关、DNS 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48639372/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com