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,太多的第一次,加油!