前言
今天玩了一天(愧疚中),写一个简单的获取自己本地ip的一个工具类,可以拿到自己的本地ip,也是这两天用了自己研究了一下,记录下来方便理解。
一、传统方式
这个是之前在网上看到的方式,自己测试了一下,其获取的是虚拟ip并不是自己想要的,因此舍弃了这种不准确的获取方式。
public static void getTraditionIp() throws UnknownHostException {
InetAddress localHost = InetAddress.getLocalHost();
String hostAddress = localHost.getHostAddress();
String hostName = localHost.getHostName();
System.out.println("传统方式-----------hostAddress = " + hostAddress);
}
二、新方式
新方式,通过NetworkInterface遍历自己本地所有接口,获取自己先要的ip。在其中可以isUp判断是否是启动状态,isVirtual 判断是否是虚拟Ip,isLoopback 判断是否是子网络接口。
public static String getLocalIp() {
try {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
ArrayList<String > list = new ArrayList<>();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
if (networkInterface.isUp()&&!networkInterface.isVirtual()&&!networkInterface.isLoopback()) {
Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
InetAddress inetAddress = inetAddresses.nextElement();
if (inetAddress instanceof Inet4Address) {
String hostAddress = inetAddress.getHostAddress();
String hostName = inetAddress.getCanonicalHostName();
list.add(hostAddress);
}
}
}
}
System.out.println("新方式--------"+list);
} catch (SocketException e) {
e.printStackTrace();
}
return null;
}
三、测试
最后测试一波,结果没说啥问题,可以看到一个数据,是我存储的我自己本地启动的一些网络ip地址,其中192.168.1.5是我目前连接WiFi的内网地址。有兴趣的小伙伴们可以试一下,直接复制就可以用。有问题的欢迎评论区留言,哈哈。
import jdk.nashorn.internal.runtime.linker.LinkerCallSite;
import java.net.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
public class getLocalIpAndRequestIp {
public static void getTraditionIp() throws UnknownHostException {
InetAddress localHost = InetAddress.getLocalHost();
String hostAddress = localHost.getHostAddress();
String hostName = localHost.getHostName();
System.out.println("传统方式-----------hostAddress = " + hostAddress);
}
public static String getLocalIp() {
try {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
ArrayList<String > list = new ArrayList<>();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
if (networkInterface.isUp()&&!networkInterface.isVirtual()&&!networkInterface.isLoopback()) {
Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
InetAddress inetAddress = inetAddresses.nextElement();
if (inetAddress instanceof Inet4Address) {
String hostAddress = inetAddress.getHostAddress();
String hostName = inetAddress.getCanonicalHostName();
list.add(hostAddress);
}
}
}
}
System.out.println("新方式--------"+list);
} catch (SocketException e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) throws UnknownHostException {
getTraditionIp();
getLocalIp();
}
}
|