62,614
社区成员
发帖
与我相关
我的任务
分享
public static String getServerIP(){
InetAddress[] inetAdds;
String serverIP = null;
try
{
inetAdds = InetAddress.getAllByName(InetAddress.getLocalHost().getHostName());
for(int i = 0 ; i < inetAdds.length; i++){
serverIP = inetAdds[i].getHostAddress();
System.out.println(serverIP );
}
}
catch (UnknownHostException e)
{
logger.error("读取IP地址异常",e);
}
return serverIP;
}
/**
* 获取本地主机IP
*
* @return
*/
public static String getLocalIP() {
InetAddress addr;
String localIP = null;
try {
addr = InetAddress.getLocalHost();
localIP = addr.getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return localIP;
}
/**
* 获取本地MAC地址
*/
public static String getLocalMAC() {
InetAddress address;
String sMAC = null;
try {
address = InetAddress.getLocalHost();
NetworkInterface ni = NetworkInterface.getByInetAddress(address);
byte[] mac = ni.getHardwareAddress();
Formatter formatter = new Formatter();
for (int i = 0; i < mac.length; i++) {
sMAC = formatter.format(Locale.getDefault(), "%02X%s", mac[i],
(i < mac.length - 1) ? "-" : "").toString();
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
}
return sMAC;
}