Com-AugustCellars / CoAP-CSharp

CoAP Implementation in C#
Other
41 stars 19 forks source link

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

Open LeeSanderson opened 3 years ago

LeeSanderson commented 3 years ago

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?