当前位置:首页 » 编程语言 » java主机名

java主机名

发布时间: 2024-10-08 05:12:55

Ⅰ 如何在java中获取本地ip

很多朋友都想知道java如何获取本地ip?下面就一起来了解一下吧~

获取java本地ip一共有两种方法:1、inetAddress类;2、封装方法。

1、 inetAddress类

通过InetAddress的实例对象包含以数字形式保存的IP地址,同时还可能包含主机名(如果使用主机名来获取InetAddress的实例,或者使用数字来构造,并且启用了反向主机名解析的功能)。InetAddress类提供了将主机名解析为IP地址(或反之)的方法。其生成InetAddress对象的方法。

import java.net.Inet4Address; import java.net.InetAddress; import java.net.UnknownHostException; public class Main {     public static void main(String[] args) throws UnknownHostException {         //Inet4Address address= (Inet4Address) Inet4Address.getLocalHost();         InetAddress address = InetAddress.getLocalHost();         System.out.println(address);//获取计算机名称和ip地址         String hostAddress = address.getHostAddress();         System.out.println(hostAddress);//获取ip地址         String hostName = address.getHostName();         System.out.println(hostName);//获取计算机名称     } }

2、封装方法。

    public static String getLocalIp() {         Enumeration  netInterfaces = null;         try {             netInterfaces = NetworkInterface.getNetworkInterfaces();             while (netInterfaces.hasMoreElements()) {                 NetworkInterface nif = netInterfaces.nextElement();                 Enumeration  InetAddress = nif.getInetAddresses();                 while (InetAddress.hasMoreElements()) {                     String ip = InetAddress.nextElement().getHostAddress();                     if (ip.startsWith("192.168")) {                         return ip;                     }                 }             }         } catch (SocketException e) {         }         return "127.0.0.1";     }

Ⅱ java如何获取当前时间,java如何获取ip地址

publicstaticvoidmain(String[]args){

try{

System.out.println("当前时间:"+newDate());

System.out.println("IP地址:"+InetAddress.getLocalHost());

}catch(UnknownHostExceptione){

e.printStackTrace();

}

}

热点内容
青云存储 发布:2025-03-21 06:50:03 浏览:401
王者荣耀有脚本吗 发布:2025-03-21 06:50:00 浏览:804
c语言代码运行 发布:2025-03-21 06:49:17 浏览:558
python打开文件夹下所有文件 发布:2025-03-21 06:44:34 浏览:949
oracle数据库表连接 发布:2025-03-21 06:42:52 浏览:44
thinkphp获取数据库 发布:2025-03-21 06:42:09 浏览:48
eclipsepythondebug 发布:2025-03-21 06:42:01 浏览:58
android获取天气 发布:2025-03-21 06:35:50 浏览:624
什么密码扣 发布:2025-03-21 06:35:17 浏览:713
如何使安卓手机秒变iphone 发布:2025-03-21 06:34:20 浏览:704