解决java网络编程IPv6问题详解编程语言

 如果系统中开启了IPV6协议(比如window7),java网络编程经常会获取到IPv6的地址,这明显不是我们想要的结果,搜索发现很多蹩脚的做法是:禁止IPv6协议。其实查看官方文档有详细的说明:

java.net.preferIPv4Stack (default: false)

If IPv6 is available on the operating system the underlying native socket
will be an IPv6 socket. This allows Java(tm) applications to connect too, and
accept connections from, both IPv4 and IPv6 hosts.

If an application has a preference to only use IPv4 sockets then this
property can be set to true. The implication is that the application will not be
able to communicate with IPv6 hosts.

在实际的运用中有以下几种办法可以实现指定获取IPv4的地址:

1、在java启动命令中增加一个属性配置:-Djava.net.preferIPv4Stack=true

java -Djava.net.preferIPv4Stack=true -cp .;classes/ michael.net.TestInetAddress 
java -Djava.net.preferIPv6Addresses=true -cp .;classes/ michael.net.TestInetAddress

2、在java程序里设置系统属性值如下:

import java.net.InetAddress; 
 
public class TestInetAddress { 
    public static void main(String[] args) throws Exception { 
 
        // 注释指定系统属性值 
        // System.setProperty("java.net.preferIPv4Stack", "true"); 
        // System.setProperty("java.net.preferIPv6Addresses", "true"); 
        System.out.println("-------InetAddress.getLocalHost()"); 
        InetAddress addr = InetAddress.getLocalHost(); 
        System.out.println("HostName := " + addr.getHostName()); 
        System.out.println("HostAddress := " + addr.getHostAddress()); 
 
        System.out.println("-------InetAddress.getByName(/"micmiu.com/")"); 
 
        InetAddress addr2 = InetAddress.getByName("micmiu.com"); 
 
        System.out.println("HostName := " + addr2.getHostName()); 
 
        System.out.println("HostAddress := " + addr2.getHostAddress()); 
    } 
}

java.net.preferIPv4Stack=true 运行结果如下:

——-InetAddress.getLocalHost() 
HostName := Michael-PC 
HostAddress := 10.7.246.163 
——-InetAddress.getByName(“micmiu.com”) 
HostName := micmiu.com 
HostAddress := 173.254.28.17

java.net.preferIPv6Addresses=true 运行结果如下:

——-InetAddress.getLocalHost() 
HostName := Michael-PC 
HostAddress := fe80:0:0:0:6518:85da:8690:16eb%13 
——-InetAddress.getByName(“micmiu.com”) 
HostName := micmiu.com 
HostAddress := 173.254.28.17

3、Tomcat Web容器

可在 catalina.bat 或者 catalina.sh 中增加如下环境变量即可:

SET CATALINA_OPTS=-Djava.net.preferIPv4Stack=true

 

原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/15915.html

(0)
上一篇 2021年7月19日
下一篇 2021年7月19日

相关推荐

发表回复

登录后才能评论