當前位置:首頁 » 編程語言 » 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();

}

}

熱點內容
sql資料庫入門到精通 發布:2025-09-13 20:13:50 瀏覽:737
微信設密碼鎖在哪裡設華為手機 發布:2025-09-13 20:04:03 瀏覽:143
電腦代理伺服器怎麼看 發布:2025-09-13 19:40:52 瀏覽:922
c語言架構 發布:2025-09-13 19:26:26 瀏覽:831
app框架源碼 發布:2025-09-13 19:17:56 瀏覽:927
sql資料庫的修復軟體 發布:2025-09-13 19:14:13 瀏覽:306
java短期培訓多少錢 發布:2025-09-13 18:32:52 瀏覽:624
鳥哥的linux私房菜架設 發布:2025-09-13 18:24:18 瀏覽:116
ts緩存編譯 發布:2025-09-13 18:14:58 瀏覽:527
哈弗h6盲區監測哪個配置有 發布:2025-09-13 17:32:39 瀏覽:203