使用Java代码,根据当前系统,自动获取当前系统的IP地址、网关和DNS信息
时间: 2024-03-02 20:49:58 浏览: 247
您可以使用Java的InetAddress和NetworkInterface类来获取当前系统的IP地址、网关和DNS信息。下面是一个示例代码:
```java
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
public class SystemInfo {
public static void main(String[] args) {
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface ni = interfaces.nextElement();
Enumeration<InetAddress> addresses = ni.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress addr = addresses.nextElement();
if (!addr.isLinkLocalAddress() && !addr.isLoopbackAddress() && addr.isSiteLocalAddress()) {
System.out.println("IP Address: " + addr.getHostAddress());
}
}
Enumeration<InetAddress> gateways = ni.getInetAddresses();
while (gateways.hasMoreElements()) {
InetAddress addr = gateways.nextElement();
if (!addr.isLinkLocalAddress() && !addr.isLoopbackAddress() && !addr.isSiteLocalAddress()) {
System.out.println("Gateway: " + addr.getHostAddress());
}
}
}
InetAddress dns = InetAddress.getByName("8.8.8.8");
System.out.println("DNS: " + dns.getHostAddress());
} catch (SocketException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
这个代码会输出当前系统的IP地址、网关和DNS信息。请注意,在获取网关地址时,我们需要排除Link-Local和Loopback地址,因为它们不是真正的网关地址。同时,在获取DNS地址时,我们使用了Google Public DNS的IP地址(8.8.8.8),您可以根据需要更改它。
阅读全文