我正在编写一些必须分别绑定(bind)到 IPv6 和 IPv4(UDP4、UDP6)的软件。我有一个可在其他地方工作的现有代码库,无法针对此任务进行修改。
Java,在其所有的荣耀中,自动创建一个可以处理 IPv6 和 IPv4 的套接字,因此当我现有的不可修改的代码尝试创建第二组套接字时,它会出错,因为该端口已在使用中。
相关:http://docs.oracle.com/javase/7/docs/technotes/guides/net/ipv6_guide/
我可以提供我拥有的代码,但认为这对回答这个问题没有帮助。非常感谢!
我的绑定(bind)函数(不是最终的生产代码):
private void bind(String uuid, String exclusiveStr, String portStr, CallbackContext c){
final JSSocket socket = socketMap.get(uuid);
boolean exclusive = Boolean.parseBoolean(exclusiveStr);
int port=0;
try{
port=Integer.parseInt(portStr);
}catch(Exception e){
//port wasn't there, use default value
}
Log.d("bind", "Attempting to bind uuid: " + uuid + " to port: " + port);
socket.bind(exclusive, port);
Log.d("bind", "new port: " + socket.getPort());
final InetAddress inetAddress = socket.getAddress();
//HashMap<String, String> setAddress= new HashMap<String,String>();
//setAddress.put("address", socket.getAddress().getHostAddress());
//setAddress.put("port", "" + socket.getPort());
JSONObject json = new JSONObject();
PluginResult result;
try {
json.put("address", socket.getAddress().getHostAddress());
json.put("port", "" + socket.getPort());
Log.d("BINDING********", json.toString());
c.success(json.toString());
}catch(JSONException e){
//todo better
e.printStackTrace();
}
}
其他代码使用 Node.js 的数据报模块。我必须写入该接口(interface)。它有单独的(我的理解)IPv4 和 IPv6 套接字。
最佳答案
在操作系统级别,这是由 IPV6_V6ONLY 标志控制的。不幸的是,java 似乎没有提供对此的任何访问。
一种可能的解决方法是绑定(bind)到单独的 IP 地址。绑定(bind)到单个 IP 地址将始终将您的套接字限制为一个 IP 版本。
关于java - 如何在Java中分别绑定(bind)IPv6和IPv4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30989638/