您好,登錄后才能下訂單哦!
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; } /** * 同步指定執(zhí)行機器的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地址 * 操作系統(tǒng)的判斷僅能判斷出是何種操作系統(tǒng),但是操作系統(tǒng)的版本就會有偏差 * 本需求僅涉及ip故忽略操作系統(tǒng)版本的偏差繼續(xù)使用 */ @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.分布式指定執(zhí)行ip初始化 try { String executeIps = xxlService.getExecuteIps(); String[] split = executeIps.split(","); if(StringUtils.isEmpty(executeIps)){ log.error("IpAddressUtil.initIp xxl未配置指定運行的ip地址信息,此處默認指定本機ip,是以最后啟動的機器ip將獲得執(zhí)行權限"); 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(); } /** * 判斷何種操作系統(tǒng) */ 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地址 問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業(yè)資訊頻道了解更多相關知識。
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。