在Java中,可以使用InetAddress
類來獲取IP地址。
以下是一些示例代碼:
import java.net.InetAddress;
public class Main {
public static void main(String[] args) {
try {
InetAddress localhost = InetAddress.getLocalHost();
System.out.println("本機IP地址: " + localhost.getHostAddress());
} catch (Exception e) {
e.printStackTrace();
}
}
}
import java.net.InetAddress;
public class Main {
public static void main(String[] args) {
try {
InetAddress address = InetAddress.getByName("www.google.com");
System.out.println("www.google.com 的IP地址: " + address.getHostAddress());
} catch (Exception e) {
e.printStackTrace();
}
}
}
注意:InetAddress.getLocalHost()
方法可能返回本機的IPv6地址,而不是IPv4地址。如果需要獲取IPv4地址,可以使用NetworkInterface
類來獲取本機的網絡接口,然后從中獲取IPv4地址。
例如:
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
public class Main {
public static void main(String[] args) {
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface networkInterface = interfaces.nextElement();
Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress address = addresses.nextElement();
if (!address.isLoopbackAddress() && address.getHostAddress().indexOf(":") == -1) {
System.out.println("本機IPv4地址: " + address.getHostAddress());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}