package com.example.utils;
import cn.hutool.core.util.StrUtil;
import org.springframework.boot.web.context.WebServerApplicationContext;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.*;
/**
* IP地址工具类
* @author 李东阳
*/
public class IpAddressUtils {
/**
* 获取项目启动的IP地址
* 注: 仅限springboot项目
**/
public static List < String > getIpAddressOfStartUp(WebServerApplicationContext context) {
List < String > addressList = new ArrayList < > ();
try {
Enumeration < NetworkInterface > interfaces = NetworkInterface.getNetworkInterfaces();
for(NetworkInterface networkInterface: Collections.list(interfaces)) {
Enumeration < InetAddress > inetAddresses = networkInterface.getInetAddresses();
for(InetAddress inetAddress: Collections.list(inetAddresses)) {
if(!inetAddress.isLoopbackAddress() && inetAddress.isSiteLocalAddress()) {
String address = StrUtil.utf8Str(inetAddress.getHostAddress());
int port = context.getWebServer().getPort();
String ipAddress = StrUtil.format("http://{}:{}", address, port);
addressList.add(ipAddress);
}
}
}
return addressList;
} catch (SocketException e) {
e.printStackTrace();
return addressList;
}
}
}
2、在启动类中使用
package com.example;
import cn.hutool.core.lang.Console;
import com.example.utils.IpAddressUtils;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.context.WebServerApplicationContext;
import org.springframework.context.annotation.Bean;
import java.util.List;
/**
* 项目启动器
* @author lidy
*/
@SpringBootApplication
public class BlogApplication {
public static void main(String[] args) {
SpringApplication.run(BlogApplication.class, args);
}
/**
* 项目启动输出访问地址
*/
@Bean
public ApplicationRunner applicationRunner(WebServerApplicationContext context) {
return (ApplicationArguments args) - > {
try {
Console.log("===============项目启动成功 start===============");
List < String > ipAddressList = IpAddressUtils.getIpAddressOfStartUp(context);
ipAddressList.forEach(Console::log);
Console.log("================项目启动成功 end================");
} catch (Exception e) {
e.printStackTrace();
}
};
}
}
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.22</version>
</dependency>