用java语言在IPV6下的socket通信编程
在java下,如果使用主机名或者dns解析来进行ipv6的socket通信编程,代码和在ipv4下一样。
客户端:
import java.net.*;
import java.io.*;
void client(String name) {
Socket s = new Socket(name, 8080);
InputStream in = s.getInputStream();
//…
in.close();
}
服务端:
ServerSocket server =new ServerSocket(port);
Socket s;
while (true) {
s = server.accept();
doClientStuff(s);
}
配置:
启动jvm时,通过带参数来设置优先使用ipv4还是ipv6地址:
-Djava.net.preferIPv4Stack=true
-Djava.net.preferIPv6Addresses=true
如果要直接使用具体的ipv6地址,则需要使用InetAddress和Inet6Address来判断和设置:
InetAddress a = InetAddress.getByName(“www.sun.com”);
/* InetAddress a = InetAddress.getByName(“2002:fe76:6523::1”); */
/* InetAddress a = InetAddress.getByName(“211.45.65.2”); */
if (a instanceof Inet6Address) {
Inet6Address a2 = (Inet6Address) a;
if (a2.isIPv4CompatibleAddress()) {
…
}
if (a2.isLinkLocalAddress()) {
…
}
}