在Java中,可以使用InetAddress
类来获取IP地址。
以下是一些示例代码:
- 获取本机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(); } } }
- 获取指定域名的IP地址:
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 { Enumerationinterfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface networkInterface = interfaces.nextElement(); Enumeration 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(); } } }