【发布时间】:2018-02-06 09:17:46
【问题描述】:
我有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 和以太网,并且我可以从两个 networkType 中获取 MAC 地址、IP 地址和所有其他值?
【问题讨论】:
-
你找到解决办法了吗?
标签: android dns ethernet gateway subnet