zoukankan      html  css  js  c++  java
  • 解决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
  • 相关阅读:
    nginx 配置https
    linux 文件上传下载
    linux系统搭建ftp服务器及创建用户使用
    Centos7.3防火墙配置
    CentOS7搭建svn部署项目
    工作中总结的常用PHP代码
    Git查看、创建、上传SSH密钥
    run `npm fund` for details found 16 vulnerabilities (2 low, 8 moderate, 6 high) run `npm audit fix` to fix them, or `npm audit` for details
    获取官方节假日数据的api接口,获取指定日期的节假日数据
    vue-elementUi项目打包后样式入坑
  • 原文地址:https://www.cnblogs.com/frankyou/p/9527886.html
Copyright © 2011-2022 走看看