1. 程式人生 > >獲取本機的內外網ip

獲取本機的內外網ip

錯誤 println subst ade 查看 imp swa ret lose

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 + "\r\n");

}

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