獲取ip的第一反應就是:使用InetAddress這個類:方法如下
InetAddress.getLocalHost().getHostAddress();
public static void main(String[] args) {
try {
//用 getLocalHost() 方法創(chuàng)建的InetAddress的對象
InetAddress address = InetAddress.getLocalHost();
System.out.println(address.getHostName());//主機名
System.out.println(address.getCanonicalHostName());//主機別名
System.out.println(address.getHostAddress());//獲取IP地址
System.out.println("===============");
//用域名創(chuàng)建 InetAddress對象
InetAddress address1 = InetAddress.getByName("www.wodexiangce.cn");
//獲取的是該網(wǎng)站的ip地址,如果我們所有的請求都通過nginx的,所以這里獲取到的其實是nginx服務器的IP地址
System.out.println(address1.getHostName());//www.wodexiangce.cn
System.out.println(address1.getCanonicalHostName());//124.237.121.122
System.out.println(address1.getHostAddress());//124.237.121.122
System.out.println("===============");
//用IP地址創(chuàng)建InetAddress對象
InetAddress address2 = InetAddress.getByName("220.181.111.188");
System.out.println(address2.getHostName());//220.181.111.188
System.out.println(address2.getCanonicalHostName());//220.181.111.188
System.out.println(address2.getHostAddress());//220.181.111.188
System.out.println("===============");
//根據(jù)主機名返回其可能的所有InetAddress對象
InetAddress[] addresses = InetAddress.getAllByName("www.baidu.com");
for (InetAddress addr : addresses) {
System.out.println(addr);
//www.baidu.com/220.181.111.188
//www.baidu.com/220.181.112.244
}
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
可以知道此時獲取到的服務器如果加了代理方式就是獲取到代理的地址,一般會使用netty代理轉(zhuǎn)發(fā)。文章來源:http://www.zghlxwxcb.cn/news/detail-505760.html
/**
* 獲取服務器IP地址
* @return
*/
@SuppressWarnings("unchecked")
public static String getServerIp(){
String SERVER_IP = null;
try {
Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
ip = (InetAddress) ni.getInetAddresses().nextElement();
SERVER_IP = ip.getHostAddress();
if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress()
&& ip.getHostAddress().indexOf(":") == -1) {
SERVER_IP = ip.getHostAddress();
break;
} else {
ip = null;
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return SERVER_IP;
}
我的解決死方法(方法是死的,但是能解決問題^_^)
在nacos的配置里面新建一個文章來源地址http://www.zghlxwxcb.cn/news/detail-505760.html
constant.ipHost=服務器的ip
//獲取服務器的ip @Value("${constant.ipHost}") private String ipHost;
到了這里,關(guān)于Java中獲取當前服務器的IP地址的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!