在网络通信中,获取本机IP地址是很重要的一步。使用Java编写程序来获取本机IP地址也是一件非常简单的事情。本文将介绍四种方式来获取本机IP地址。
一、通过InetAddress类获取
使用InetAddress类可以得到本机的IP地址。
import java.net.InetAddress;
public class GetIpAddressByInetAddress {
public static void main(String[] args) throws Exception {
InetAddress address = InetAddress.getLocalHost();
System.out.println("本机IP地址为:" + address.getHostAddress());
}
}
以上代码的输出为:
本机IP地址为:192.168.1.112
二、通过NetworkInterface类获取
使用NetworkInterface类获取本机IP地址比 InetAddress 更加灵活和准确。我们可以针对每个网络接口,获取对应的IP地址。
import java.net.*;
import java.util.Enumeration;
public class GetIpAddressByNetworkInterface {
public static void main(String[] args) throws Exception {
Enumeration<NetworkInterface> niList = NetworkInterface.getNetworkInterfaces();
while (niList.hasMoreElements()) {
NetworkInterface ni = niList.nextElement();
Enumeration<InetAddress> addrList = ni.getInetAddresses();
while (addrList.hasMoreElements()) {
InetAddress address = addrList.nextElement();
if (!address.isLinkLocalAddress() && !address.isLoopbackAddress() && address instanceof Inet4Address) {
System.out.println("本机IP地址为:" + address.getHostAddress());
}
}
}
}
}
以上代码的输出为:
本机IP地址为:192.168.1.112
三、通过System类获取
通过System类获取本机IP地址可以使用java.net.InetAddress类的静态方法getLocalHost()获取到本地IP地址。
import java.net.InetAddress;
public class GetIpAddressBySystem {
public static void main(String[] args) throws Exception {
InetAddress address = InetAddress.getLocalHost();
System.out.println("本机IP地址为:" + address.getHostAddress());
}
}
以上代码的输出为:
本机IP地址为:192.168.1.112
四、通过网站获取
我们可以通过一个在线网站来获取我们的公网IP地址。这种方式的缺点是需要联网。如果是需要获取内网IP地址的话,这种方式则无效。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
public class GetIpAddressByWeb {
public static void main(String[] args) throws Exception {
URL url = new URL("http://checkip.amazonaws.com");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String ipAddress = in.readLine().trim();
System.out.println("公网IP地址为:" + ipAddress);
}
}
以上代码的输出为:
公网IP地址为:175.86.175.31
以上就是使用Java获取本机IP地址的四种方式。如果您还有其他方式,欢迎在评论区分享。