您的位置:首页 > 本地本地

如何在java中获取本地ip

admin2024-07-09人已围观

很多朋友都想知道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;     }

很赞哦! ()

上一篇:求一款WIN7系统可以用的中文版的 TXT小说阅读器!'>谈谈自媒体、新媒体和融媒体

下一篇:返回列表'>返回列表

随机图文