Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unable to bind CoapServer to the same IP address using different ports. #87

Open
LeeSanderson opened this issue Feb 11, 2021 · 0 comments

Comments

@LeeSanderson
Copy link

This code:

var server = new CoapServer();
server.AddEndPoint(new CoAPEndPoint(new IPEndPoint(IPAddress.Parse("0.0.0.0"), 5683)));
server.AddEndPoint(new DTLSEndPoint(null, sharedKeys, new IPEndPoint(IPAddress.Parse("0.0.0.0"), 5684)));
server.Start();

Fails with an error "Object reference not set to an instance of an object." at Com.AugustCellars.CoAP.DTLS.DTLSChannel.Stop()
This error needs to be fixed as it is actually obfuscating the underlying problem.

The real problem is in SocketSet.Find code. The current implementation is shown below:

        public static SocketSet Find(IPEndPoint endPoint)
        {
            if (endPoint.Port != 0) {
                foreach (SocketSet s in allSockets) {
                    if (((endPoint.Port == s.Port) && (s.LocalEP == null)) ||
                        (s.LocalEP != null &&
                         ((endPoint.AddressFamily == s.LocalEP.AddressFamily) &&
                          (endPoint.Address.Equals(s.LocalEP.Address))))) {
                        return s;
                    }
                }
            }

            return null;
        }

This causes the UDPChannel constructor to throw an exception "Cannot open the same address twice" - even though the addresses are on different ports.

I recommend the following change (basically match an end point if it is on the same port and either the LocalEP address is null or the LocalEP matches and existing endpoint)

        public static SocketSet Find(IPEndPoint endPoint)
        {
            if (endPoint.Port != 0)
            {
                foreach (SocketSet s in allSockets)
                {
                    if (endPoint.Port == s.Port && 
                        (s.LocalEP == null ||
                        (s.LocalEP != null && endPoint.AddressFamily == s.LocalEP.AddressFamily && endPoint.Address.Equals(s.LocalEP.Address))))
                    {
                        return s;
                    }
                }
            }

            return null;
        }

Are there any obvious issues with this solution?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant