新网创想网站建设,新征程启航
为企业提供网站建设、域名注册、服务器等服务
可以使用 InetAddress.getLocalHost(),代码如下:
创新互联公司自2013年起,先为裕华等服务建站,裕华等地企业,进行企业商务咨询服务。为裕华企业网站制作PC+手机+微官网三网同步一站式服务解决您的所有建站问题。
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);
}
}
结果如下:
//看看这个代码如何。
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虚拟机和系统的信息。
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;
}
}
这个代码简单明了,就是调用现成的InetAddress类