可以使用 InetAddress.getLocalHost(),代碼如下:
創(chuàng)新互聯(lián)公司自2013年起,先為裕華等服務(wù)建站,裕華等地企業(yè),進行企業(yè)商務(wù)咨詢服務(wù)。為裕華企業(yè)網(wǎng)站制作PC+手機+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問題。
import?java.net.*;
public?class?App?{
public?static?void?main(String[]?args)?throws?UnknownHostException?{
InetAddress?local?=?InetAddress.getLocalHost();
System.out.println("計算機名:"?+?local.getHostName());
System.out.println("IP:"?+?local.getHostAddress());
}
}
java獲取機器名,主要是使用InterAddress類,如下代碼:
package?com.qiu.lin.he;
import?java.net.InetAddress;
public?class?Ceshi?{
public?static?void?main(String[]?args)?{
InetAddress?addr?=?null;
String?address?=?"";
try?{
addr?=?InetAddress.getLocalHost();//新建一個InetAddress類
address?=?addr.getHostName().toString();//?獲得本機名稱
}?catch?(Exception?e)?{
e.printStackTrace();
}
System.out.println(address);
}
}
結(jié)果如下:
//看看這個代碼如何。
import?java.net.InetAddress;
import?java.net.UnknownHostException;
import?java.util.Properties;
import?java.util.Set;
public?class?TestSystemProperties?{
public?static?void?main(String?[]?args){
InetAddress?netAddress?=?getInetAddress();
System.out.println("host?ip:"?+?getHostIp(netAddress));
System.out.println("host?name:"?+?getHostName(netAddress));
Properties?properties?=?System.getProperties();
SetString?set?=?properties.stringPropertyNames();?//獲取java虛擬機和系統(tǒng)的信息。
for(String?name?:?set){
System.out.println(name?+?":"?+?properties.getProperty(name));
}
}
public?static?InetAddress?getInetAddress(){
try{
return?InetAddress.getLocalHost();
}catch(UnknownHostException?e){
System.out.println("unknown?host!");
}
return?null;
}
public?static?String?getHostIp(InetAddress?netAddress){
if(null?==?netAddress){
return?null;
}
String?ip?=?netAddress.getHostAddress();?//get?the?ip?address
return?ip;
}
public?static?String?getHostName(InetAddress?netAddress){
if(null?==?netAddress){
return?null;
}
String?name?=?netAddress.getHostName();?//get?the?host?address
return?name;
}
}
這個代碼簡單明了,就是調(diào)用現(xiàn)成的InetAddress類