publicstaticvoidmain(String[]args)throws UnknownHostException{InetAddress localHost=InetAddress.getLocalHost();System.out.println(localHost.getHostAddress());System.out.println("---下面才是正确的获取方式---");localHost=getLocalHostExactAddress();System.out.println(localHost.getHostAddress());// System....
Java提供了InetAddress类来代表IP地址,InetAddress下还有两个子类:Inet4Address、Inet6Address,它们分别代表Internet Protocol version 4(IPv4)地址和Internet Protocol version 6(IPv6)地址。 InetAddress常用方法: 验证是否可达: boolean isReachable(int timeout):等价于isReachable(null, 0 , timeout) boolean isRea...
(127.x.x.x) boolean isLinkLocalAddress():检查 InetAddress 是否为链路本地地址的实用程序例程。(169.254.0.0/16) 代码案例如下: publicvoidinetAddressTest()throwsIOException {// 根据域名来获取对应的InerAddress实例InetAddressip=InetAddress.getByName("www.baidu.com");// 判断是否可达System.out.println("...
Java.net包中有InetAddress类的定义,InetAddress类的对象用于IP地址和域名,该类提供以下方法: getByName(String s):获得一个InetAddress 类的对象,该对象中含有主机的IP地址和域名,该对象用如下格式表示它包含的信息:www.sina.com.cn/202.108.37.40; String getHostName():获取InetAddress对象的域名; String getHost...
Java 输出通过 InetAddress 获得的 IP 地址数组 使用InetAddress 获取 IP 地址会得到一个 byte 数组 如果你直接输出这个数组,你会发现 IP 地址中的某些位变成了负数 比如61.135.169.105 会输出成 61.-121.-87.105 仔细看一看,会发现 135 + 121 = 256,169 + 87 = 256...
在执行程序时,确实遇到了一个棘手的问题,具体表现为在尝试通过InetAddress objAddr=InetAddress.getLocalHost();获取本机IP地址时,程序抛出了异常。根据我的调试结果,本机的IP地址应该是172.16.43.84,并且IP地址的版本是IPv4。这让我意识到,可能是因为在同一台机器上同时配置了IPv6和IPv4地址,...
为了更好的解释为何InetAddress#getLocalHost()不靠谱,有必要先普及下Linux下的相关文件的解释,比较我们的Java应用绝大部分情况下都是跑在Linux环境下的(甚至国内基本都跑在centos上吧)。 Linux下/sysconfig/network、hosts、host.conf、resolv.conf文件解释 ...
importjava.util.Scanner;publicclassMain{publicstaticvoidmain(String[]args){Scannerscanner=newScanner(System.in);System.out.print("请输入IPv6地址:");Stringipv6Address=scanner.nextLine();// 下一步的代码将在此处添加}} 1. 2. 3. 4. 5. ...
2. Java IPv4 Regex Validator Below is a Java IPv4 regex validator example. It uses the above IPv4 regex version 5 to validation an IPv4 address. IPv4ValidatorRegex.java packagecom.mkyong.regex.ipv4;importjava.util.regex.Matcher;importjava.util.regex.Pattern;publicclassIPv4ValidatorRegex{privatestati...
System.out.print("The IP address "+INET6ADDRESS+" isn't valid"); } } } Download Code Output: The IP address 172.8.9.28 is valid The IP address 2001:0db8:85a3:0000:0000:8a2e:0370:7334 is valid 4. Using Java 8 In Java 8, we can simplify things with the help of Stream, as ...