java獲取IP地址
最近公司在做日誌報警服務,並將異常信息推送到簡聊,需要在異常信息上添加IP地址,用於快速定位異常位置。總結以下知識點:
- 獲取本地IP地址
String address = InetAddress.getLocalHost().getHostAddress().toString();
這種方法能不能在Linux服務器上直接獲取IP有待驗證
- 獲取服務器IP地址
/**
* 設置異常信息
* @param t 異常信息。注意:這裏使用的是Throwable來接收參數,爲什麼不是使用Exception?
* 因爲使用Exception接收的話,不好獲取具體的異常信息,所以這裏使用Throwable來接收,然後再
* 通過流的形式獲取具體的異常信息
*/
public void setMsg(Throwable t) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
t.printStackTrace(new PrintStream(stream));
String exceptionMsg = stream.toString();
log.error(exceptionMsg); // 記錄到本地日誌
JSONObject obj = new JSONObject();
obj.element("authorName", "異常報警");
obj.element("title", "IP爲" + getServerIp() + "的又TM異常啦:");
obj.element("text", exceptionMsg);
post(obj);
}
/**
* 推送異常日誌信息,
* @param json 請求參數是用 net.sf.json.JSONObject 封裝
*/
public void post(JSONObject json) {
HttpClient client;
HttpPost post;
try {
client = HttpClients.createDefault();
post = new HttpPost(logServer); // logServer 是簡聊的聚合服務地址
post.setHeader("Content-Type", "application/json");
post.addHeader("Authorization", "Basic YWRtaW46");
StringEntity s = new StringEntity(json.toString(), "utf-8");
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(s);
// 發送請求
HttpResponse httpResponse = client.execute(post);
if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
log.info("請求服務器失敗,請檢查推送服務器");
}
} catch (Exception e) {
log.error("推送日誌異常信息失敗");
e.printStackTrace();
}
}
/**
* 獲取服務器地址
*
* @return Ip地址
*/
public String getServerIp() {
// 獲取操作系統類型
String sysType = System.getProperties().getProperty("os.name");
String ip;
if (sysType.toLowerCase().startsWith("win")) { // 如果是Windows系統,獲取本地IP地址
String localIP = null;
try {
localIP = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
log.error(e.getMessage(), e);
}
if (localIP != null) {
return localIP;
}
} else {
ip = getIpByEthNum("eth0"); // 兼容Linux
if (ip != null) {
return ip;
}
}
return "獲取服務器IP錯誤";
}
/**
* 根據網絡接口獲取IP地址
* @param ethNum 網絡接口名,Linux下是eth0
* @return
*/
private String getIpByEthNum(String ethNum) {
try {
Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip;
while (allNetInterfaces.hasMoreElements()) {
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
if (ethNum.equals(netInterface.getName())) {
Enumeration addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
ip = (InetAddress) addresses.nextElement();
if (ip != null && ip instanceof Inet4Address) {
return ip.getHostAddress();
}
}
}
}
} catch (SocketException e) {
logger.error(e.getMessage(), e);
}
return "獲取服務器IP錯誤";
}
第一次寫博客,第一次用MarkDown,太多的第一次,加油!