shy*_*002 5 dns android ethernet gateway subnet
我有通过以太网连接的Android PC 设备、手持设备。现在我能够获取设备的 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();
}
Run Code Online (Sandbox Code Playgroud)
以下两个问题可能与您无关,但我已经记在心里了,所以请任何人解释一下,我将不胜感激。
1)如果我同时有WIFI连接和以太网连接,那么我如何识别我的应用程序连接到服务器的连接。(除了我使用的网络类型代码)?
2)是否有可能设备中同时连接了 WiFi 和以太网,并且我可以从两个网络类型获取 mac 地址、ip 地址和所有其他值?
小智 -3
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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1710 次 |
| 最近记录: |