问题
I'm writing a Network Framework prototype in Java using UDP to deal with moments where a device using it might not have a permanent and/or reliable connection and how it should deal with it. It is required that I have to be able to use it with "normal" IPv4 and IPv6 addresses as well as IPv6 LinkLocal Addresses.
Due to the concept there's moments where the device loses connectivity and i have to close all DatagramSockets binded to a specific IP/Port pair so i can free resources and, once the device gets a new connection, i need to "rebind" the sockets to the given Addresses.
There's no problems with the code when I'm testing with "normal" IPv4 and IPv6 addresses but once i start using IPv6 LinkLocal addresses I get this exception when I try to rebind a DatagramSocket to any LinkLocal address:
java.net.BindException: Cannot assign requested address (Bind failed)
at java.base/java.net.PlainDatagramSocketImpl.bind0(Native Method)
at java.base/java.net.AbstractPlainDatagramSocketImpl.bind(AbstractPlainDatagramSocketImpl.java:131)
at java.base/java.net.DatagramSocket.bind(DatagramSocket.java:394)
Since this code works for non LinkLocal Addresses i assumed it would work for LinkLocal addresses too.
Here's the code i use to bind a DatagramSocket to a IP/Port pair:
private void bindDatagramSocket() {
try {
this.ds = new DatagramSocket(null);
InetSocketAddress isa = new InetSocketAddress(this.ip, this.port);
this.ds.bind(isa);
this.hasConnection = true;
}
catch (SocketException e) {
e.printStackTrace();
}
Where this.ip and this.port are updated by another Thread that detects a change in the available Addresses and connection status (with/without connection). When a connection loss is detected I use this code to close the DatagramSocket in use (this.ds)
public void updateConnectionStatus(boolean value){
this.connectionLock.lock();
this.hasConnection = value;
this.connectionLock.unlock();
if(value && !this.isRunning){
new Thread(this).start();
}
else{
if(!value) {
this.ds.close();
this.ds = null;
}
}
Any suggestions are appreciated
TL;DR: Using DatagramSockets to bind to an IP/Port pair corresponding to a IPv6 LinkLocal Address, closing that DatagramSocket and rebinding it to the same IPv6 LinkLocal Address results in Exception even though the same code works for any other case I can test with "normal" IPv4 and IPv6 Addresses
来源:https://stackoverflow.com/questions/64719587/java-net-bindexception-cannot-assign-requested-address-bind-failed-on-linkloc