获取本机的内外网ip
Posted tk112
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了获取本机的内外网ip相关的知识,希望对你有一定的参考价值。
package tool;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* @description
* @author: 123.com
* @create: 2019-01-17 17:34:52
**/
public class GetIp {
public static void getip() {
try {
InetAddress address = InetAddress.getLocalHost();//获取的是本地的IP地址 //PC-20140317PXKX/192.168.0.121
String hostAddress = address.getHostAddress();//192.168.0.121
InetAddress address1 = InetAddress.getByName("www.wodexiangce.cn");//获取的是该网站的ip地址,比如我们所有的请求都通过nginx的,所以这里获取到的其实是nginx服务器的IP地
String hostAddress1 = address1.getHostAddress();//124.237.121.122
InetAddress[] addresses = InetAddress.getAllByName("www.baidu.com");//根据主机名返回其可能的所有InetAddress对象
for(InetAddress addr:addresses){
System.out.println(addr);//www.baidu.com/14.215.177.38
//www.baidu.com/14.215.177.37
}
} catch (Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) {
String serverIp = getServerIp();
System.out.println(serverIp);
}
/**
* 获取服务器IP地址
* @return
*/
@SuppressWarnings("unchecked")
public static String getServerIp(){
InetAddress addr = null;
try {
addr = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] ipAddr = addr.getAddress();
String ipAddrStr = "";
for (int i = 0; i < ipAddr.length; i++) {
if (i > 0) {
ipAddrStr += ".";
}
ipAddrStr += ipAddr[i] & 0xFF;
}
//System.out.println(ipAddrStr);
return "局域网:"+ipAddrStr;
}
}
/***************************************************分割线******************************************************/
package tool;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
public class Getip2 {
public static String getWebIp() {
try {
//如果请求超时 ,请查看查询本机IP网站 是否更换
URL url = new URL("http://2018.ip138.com/ic.asp");
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
String s = "";
StringBuffer sb = new StringBuffer("");
String webContent = "";
while ((s = br.readLine()) != null) {
sb.append(s + "
");
}
br.close();
webContent = sb.toString();
int start = webContent.indexOf("[")+1;
int end = webContent.indexOf("]");
webContent = webContent.substring(start,end);
return webContent;
} catch (Exception e) {
System.err.println("获取IP发生错误");
e.printStackTrace();
return "error";
}
}
public static void main(String [] args) throws IOException {
String ip = Getip2.getWebIp();
// System.out.println(ip);
String str ="";
StringBuilder sb = new StringBuilder(ip);
sb.replace(12,15,str);
System.out.println("所属外网:" + sb.toString());
String serverIp = GetIp.getServerIp();
System.out.println(serverIp);
}
}
以上是关于获取本机的内外网ip的主要内容,如果未能解决你的问题,请参考以下文章
第二十九节: Asp.Net Core零散总结(各种目录内外网ip)[不断补充]