解决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

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

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

1 package michael.net;
2  
3 import java.net.InetAddress;
4  
5 /**
6  * @blog http://www.micmiu.com
7  * @author Michael
8  */
9 public class TestInetAddress {
10  
11     /**
12      * @param args
13      */
14     public static void main(String[] args) throws Exception {
15         // 注释指定系统属性值
16         // System.setProperty("java.net.preferIPv4Stack", "true");
17         // System.setProperty("java.net.preferIPv6Addresses", "true");
18         System.out.println("-------InetAddress.getLocalHost()");
19         InetAddress addr = InetAddress.getLocalHost();
20         System.out.println("HostName := " + addr.getHostName());
21         System.out.println("HostAddress := " + addr.getHostAddress());
22  
23         System.out.println("-------InetAddress.getByName(\"micmiu.com\")");
24         InetAddress addr2 = InetAddress.getByName("micmiu.com");
25         System.out.println("HostName := " + addr2.getHostName());
26         System.out.println("HostAddress := " + addr2.getHostAddress());
27  
28     }
29 }

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

你可能感兴趣的:(玩转,Java)