若是系統中開啓了IPV6協議(好比window7),java網絡編程常常會獲取到IPv6的地址,這明顯不是咱們想要的結果,搜索發現不少蹩腳的作法是:禁止IPv6協議。其實查看官方文檔有詳細的說明:java
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.app
在實際的運用中有如下幾種辦法能夠實現指定獲取IPv4的地址:socket
java -Djava.net.preferIPv4Stack=true -cp .;classes/ michael.net.TestInetAddress java -Djava.net.preferIPv6Addresses=true -cp .;classes/ michael.net.TestInetAddress
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 運行結果以下:this
——-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 運行結果以下:spa
——-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
可在 catalina.bat 或者 catalina.sh 中增長以下環境變量便可:.net
SET CATALINA_OPTS=-Djava.net.preferIPv4Stack=true