java中怎么获取ip地址 ,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
package com.ysma.jobs.util;
import com.ysma.jobs.common.component.RedisManager;
import com.ysma.jobs.common.constants.CacheKeyConstants;
import com.ysma.jobs.common.dingtalk.ChatbotSend;
import com.ysma.jobs.service.XxlService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.concurrent.TimeUnit;
/**
* IP地址获取工具
* @Date: 2019/6/17 14:26
* modified by ysma 2019-06-28
*/
@DependsOn(value = {"redisManager", "chatbotSend", "xxlService"})
@Component
@Slf4j
public class IpAdressUtil {
@Autowired
private ChatbotSend chatbotSend;
@Autowired
private XxlService xxlService;
@Autowired
private RedisManager redisManager;
/**定义一个static的ip变量,使得其全栈可见*/
private static volatile String MACHINE_IP;
private final String OS_WINDOWS = "windows";
private final String OS_MAC = "mac";
public String getServerIp(){
if(StringUtils.isEmpty(MACHINE_IP)){
log.error("IpAddressUtil.getServerIp 为获取到服务器ip,MACHINE_IP:{}", MACHINE_IP);
return null;
}
return MACHINE_IP;
}
/**
* 同步指定执行机器的ip地址到redis,以便所有机器共享此信息,进行协同
* @param ip ip地址
*/
private void setJobRunIP(String ip){
String key = CacheKeyConstants.JOB_DEFAULT_RUN_IP;
boolean result = redisManager.set(key, ip);
log.info("IpAddressUtil.setJobRunIP set job running ip runIp:{}, result:{}" , ip, result);
}
/**
* 获取本地IP地址
* 操作系统的判断仅能判断出是何种操作系统,但是操作系统的版本就会有偏差
* 本需求仅涉及ip故忽略操作系统版本的偏差继续使用
*/
@PostConstruct
public void initIp() {
//
Thread initIpThread = new Thread(() -> {
//1.本地ip地址初始化
boolean goOn = true;
do {
MACHINE_IP = getMachineIp();
try {
goOn = StringUtils.isEmpty(MACHINE_IP);
if(goOn){//钉钉告警直到获取到ip地址
chatbotSend.sendMsg("请注意,scheduler应用当前未获取到ip地址! 5秒后重试");
TimeUnit.SECONDS.sleep(5);
}
} catch (Exception ex) {
log.error("IpAddressUtil.initIp Exception V_V", ex);
}
} while (goOn);//直到获取到本地ip 停止
//2.分布式指定执行ip初始化
try {
String executeIps = xxlService.getExecuteIps();
String[] split = executeIps.split(",");
if(StringUtils.isEmpty(executeIps)){
log.error("IpAddressUtil.initIp xxl未配置指定运行的ip地址信息,此处默认指定本机ip,是以最后启动的机器ip将获得执行权限");
setJobRunIP(MACHINE_IP);
} else {
setJobRunIP(split[0]);
}
Object runIp = redisManager.get(CacheKeyConstants.JOB_DEFAULT_RUN_IP);
log.info("IpAddressUtil.initIp 本机ip:{}, 指定运行ip:{}", MACHINE_IP,
runIp == null ? "": runIp.toString());
} catch (Exception ex) {
log.error("IpAddressUtil.initIp Exception V_V", ex);
}
});
initIpThread.setName("init-ip-thread");
initIpThread.start();
}
/**
* 判断何种操作系统
*/
private boolean isThisOS(String prefixName) {
String osName = System.getProperty("os.name");
return osName.toLowerCase().startsWith(prefixName);
}
/**
* 获取机器的IP地址
*/
private String getMachineIp() {
String ipString = null;
try {
if(isThisOS(OS_WINDOWS)){
ipString = InetAddress.getLocalHost().getHostAddress();
log.info("IpAddressUtil.getMachineIp windows os, ip:{}", ipString);
} else {
Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
boolean findFlag = false;
while (netInterfaces.hasMoreElements()) {
if(findFlag){
break;
}
NetworkInterface ni = netInterfaces.nextElement();
Enumeration<InetAddress> ips = ni.getInetAddresses();
while (ips.hasMoreElements()) {
InetAddress address = ips.nextElement();
if( address.isSiteLocalAddress()
&& !address.isLoopbackAddress() //127.开头的都是lookback地址
&& !address.getHostAddress().contains(":")){
ipString = address.getHostAddress();
findFlag = true;
break;
}
}
}
log.info("IpAddressUtil.getMachineIp {} os, ip:{}",
isThisOS(OS_MAC) ? "Mac" : "linux/unix",
ipString);
}
} catch (Exception ex) {
log.error("IpAddressUtil.getMachineIp error", ex);
}
return ipString;
}
}
关于java中怎么获取ip地址 问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/ysma1987/blog/3069386