java.net.BindException: Cannot assign requested address (Bind failed) on LinkLocal rebind

↘锁芯ラ 提交于 2021-01-05 06:01:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!