温馨提示×

java如何获取ip地址

小亿
95
2024-01-16 15:03:59
栏目: 编程语言

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

以下是一些示例代码:

  1. 获取本机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();
        }
    }
}
  1. 获取指定域名的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();
        }
    }
}

0