Java调取底层命令获取主机名(localhostName)

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Enumeration;


import com.comisys.gudong.logging.Logger;


public class RuntimeEnvUtil {


/**
* @author fsl
* @return
*/
//获取本机的主机名
public static String getHostNameM(){
if(logger.isDebugEnabled()){
logger.debug("debug getHostName begin");
}
String name =getHostName();
logger.debug("host name:"+name);

if("localhost".equals(name)){
return getServerIp();
}
if(logger.isDebugEnabled()){
logger.debug("debug getHostName end");
}
return name;

}

public static String getHostName(){
try {
Process p = Runtime.getRuntime().exec("hostname");
BufferedInputStream in = new BufferedInputStream(p.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(in));
 
    String line=null;  
    //只需要取出第一行
    if((line=br.readLine())!=null)  
    {  
      return line;
    }  


    br.close();  
    p.destroy();  
    return line; 


} catch (IOException e) {
  if(logger.isErrorEnabled()){
  logger.error("IOException", e);
  }
}

return null;
}
//获取本地的非127.0.0.1的ip地址
public static String  getServerIp(){
String SERVER_IP=null;
    try {
Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;

while (netInterfaces.hasMoreElements()) {
boolean flag = false;
NetworkInterface ni = (NetworkInterface) netInterfaces
.nextElement();
//判断 接口名字中不包含:的
//System.out.println(ni.getName()+"-----");
logger.debug(ni.getName()+"-----");
if(!ni.getName().contains(":")){
   Enumeration<InetAddress> inetAddresses = ni.getInetAddresses();   
while (inetAddresses.hasMoreElements()) {   
                   ip = inetAddresses.nextElement(); 
                   //!ip.isSiteLocalAddress()    判断信息是否源自本机的ip
                if (!ip.isLoopbackAddress()&& ip.getHostAddress().indexOf(":") == -1) {
SERVER_IP = ip.getHostAddress();
flag = true;
break;
} else {
ip = null;
}  
}
}
 
if(flag){
break;
    }
}
} catch (Exception e) {
logger.error("unknown host",e);
}
     return SERVER_IP;
   }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值