java代码获取本机ip(java代码获取本机ip地址)

简介

获取本机IP地址是Java程序设计中一项常见任务,它允许应用程序了解自己的网络配置并与其他计算机进行通信。

多级标题

### 获取IPv4地址IPv4地址是32位数字,表示互联网协议版本4中的网络接口地址。以下Java代码可用于获取IPv4地址:```java import java.net.InetAddress;public class GetLocalIPv4Address {public static void main(String[] args) throws Exception {InetAddress address = InetAddress.getLocalHost();System.out.println("IPv4 address: " + address.getHostAddress());} } ```### 获取IPv6地址IPv6地址是128位数字,表示互联网协议版本6中的网络接口地址。以下Java代码可用于获取IPv6地址:```java import java.net.NetworkInterface; import java.util.Collections; import java.util.Enumeration;public class GetLocalIPv6Address {public static void main(String[] args) throws Exception {Enumeration interfaces = NetworkInterface.getNetworkInterfaces();for (NetworkInterface interf : Collections.list(interfaces)) {if (interf.isUp() && !interf.isLoopback()) {Enumeration addresses = interf.getInetAddresses();while (addresses.hasMoreElements()) {InetAddress address = addresses.nextElement();if (address instanceof Inet6Address) {System.out.println("IPv6 address: " + address.getHostAddress());}}}}} } ```### 获取所有IP地址以下Java代码可用于获取本机所有IP地址(包括IPv4和IPv6):```java import java.net.InetAddress;public class GetAllLocalIPAddresses {public static void main(String[] args) throws Exception {InetAddress[] addresses = InetAddress.getAllByName(InetAddress.getLocalHost().getHostName());for (InetAddress address : addresses) {System.out.println("IP address: " + address.getHostAddress());}} } ```

**简介**获取本机IP地址是Java程序设计中一项常见任务,它允许应用程序了解自己的网络配置并与其他计算机进行通信。**多级标题**

获取IPv4地址IPv4地址是32位数字,表示互联网协议版本4中的网络接口地址。以下Java代码可用于获取IPv4地址:```java import java.net.InetAddress;public class GetLocalIPv4Address {public static void main(String[] args) throws Exception {InetAddress address = InetAddress.getLocalHost();System.out.println("IPv4 address: " + address.getHostAddress());} } ```

获取IPv6地址IPv6地址是128位数字,表示互联网协议版本6中的网络接口地址。以下Java代码可用于获取IPv6地址:```java import java.net.NetworkInterface; import java.util.Collections; import java.util.Enumeration;public class GetLocalIPv6Address {public static void main(String[] args) throws Exception {Enumeration interfaces = NetworkInterface.getNetworkInterfaces();for (NetworkInterface interf : Collections.list(interfaces)) {if (interf.isUp() && !interf.isLoopback()) {Enumeration addresses = interf.getInetAddresses();while (addresses.hasMoreElements()) {InetAddress address = addresses.nextElement();if (address instanceof Inet6Address) {System.out.println("IPv6 address: " + address.getHostAddress());}}}}} } ```

获取所有IP地址以下Java代码可用于获取本机所有IP地址(包括IPv4和IPv6):```java import java.net.InetAddress;public class GetAllLocalIPAddresses {public static void main(String[] args) throws Exception {InetAddress[] addresses = InetAddress.getAllByName(InetAddress.getLocalHost().getHostName());for (InetAddress address : addresses) {System.out.println("IP address: " + address.getHostAddress());}} } ```

标签列表