Skip to content

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

Description

@LeeSanderson

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?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions