我有通过以太网连接连接的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地址,ipaddress和所有其他值?
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;
}