java如何获取ip地址

   2025-02-05 6960
核心提示:在Java中,可以使用InetAddress类来获取IP地址。以下是一些示例代码:获取本机IP地址:import java.net.InetAddress;public clas

在Java中,可以使用InetAddress类来获取IP地址。

以下是一些示例代码:

获取本机IP地址:
import java.net.InetAddress;public class Main {    public static void main(String[] args) {        try {            InetAddress localhost = InetAddress.getLocalHost();            System.out.println("本机IP地址: " + localhost.getHostAddress());        } catch (Exception e) {            e.printStackTrace();        }    }}
获取指定域名的IP地址:
import java.net.InetAddress;public class Main {    public static void main(String[] args) {        try {            InetAddress address = InetAddress.getByName("www.google.com");            System.out.println("www.google.com 的IP地址: " + address.getHostAddress());        } catch (Exception e) {            e.printStackTrace();        }    }}

注意:InetAddress.getLocalHost()方法可能返回本机的IPv6地址,而不是IPv4地址。如果需要获取IPv4地址,可以使用NetworkInterface类来获取本机的网络接口,然后从中获取IPv4地址。

例如:

import java.net.InetAddress;import java.net.NetworkInterface;import java.util.Enumeration;public class Main {    public static void main(String[] args) {        try {            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();            while (interfaces.hasMoreElements()) {                NetworkInterface networkInterface = interfaces.nextElement();                Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();                while (addresses.hasMoreElements()) {                    InetAddress address = addresses.nextElement();                    if (!address.isLoopbackAddress() && address.getHostAddress().indexOf(":") == -1) {                        System.out.println("本机IPv4地址: " + address.getHostAddress());                    }                }            }        } catch (Exception e) {            e.printStackTrace();        }    }}

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言