public static void main(String[] args) {
try {
System.out.println("当前时间:"+new Date());
System.out.println("IP地址 : " + InetAddress.getLocalHost());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
获取当前时间
public static void main(String[] args) throws IOException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(format.format(new Date()));
}
获取ip地址
public static void main(String[] args) throws IOException {
InetAddress netAddress = InetAddress.getLocalHost();
System.out.println("ip地址: " + netAddress.getHostAddress());
System.out.println("主机名: " + netAddress.getHostName());
}
其实使用InetAddress.getLocalHost()获取ip存在问题,因为有的电脑有多个网卡,也就有多个ip地址,正确的方法应该是这样
public static void main(String[] args) throws IOException {
Listresult = new ArrayList ();
EnumerationnetInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip;
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = netInterfaces.nextElement();
Enumerationaddresses = ni.getInetAddresses();
while (addresses.hasMoreElements()) {
ip = addresses.nextElement();
if (!ip.isLoopbackAddress() && ip.getHostAddress().indexOf(':') == -1) {
result.add(ip.getHostAddress());
}
}
}
for (String string : result) {
System.out.println(string);
}
}
使用jdk提供的api NetworkInterface,可以将主机的所有网卡的ip地址全部获取,比如无线网卡、有线网卡、蓝牙等等