如何在java中获取本地ip

来源:趣味经验馆 4.98K
<link rel="stylesheet" href="https://js.how234.com/third-party/SyntaxHighlighter/shCoreDefault.css" type="text/css" /><script type="text/javascript" src="https://js.how234.com/third-party/SyntaxHighlighter/shCore.js"></script><script type="text/javascript"> SyntaxHighlighter.all(); </script>

很多朋友都想知道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);//获取计算机名称    }}

如何在java中获取本地ip

2、封装方法。

    public static String getLocalIp() {        Enumeration<NetworkInterface> netInterfaces = null;        try {            netInterfaces = NetworkInterface.getNetworkInterfaces();            while (netInterfaces.hasMoreElements()) {                NetworkInterface nif = netInterfaces.nextElement();                Enumeration<InetAddress> 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";    }
热门标签