如果系統中開啟了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