Search code examples
c#networkingudpudpclient

How to run client and server UDP listeners on the same machine


Both client and server send and receive on a given port. In production they are on separate machines and there is no problem. In development it would be a great deal more convenient to run them on the same machine and avoid the need for deployment and setting up and tearing down a remote debug session.

I tried this

var uc = new UdpClient();
var ep = new IPEndPoint(address, port);
uc.ExclusiveAddressUse = false;
uc.Client.Bind(ep);

and it doesn't barf but I still can't bind multiple listeners to the same endpoint. After the fact I discovered that ExclusiveAddressUse defaults to false anyhow so this approach produces nothing but extra code.

Is this possible and if so how?


Solution

  • You obviously cant use the same port on the same machine, just use an #if directive for debug and change your ports accordingly

    The following might help

    Client

    #if DEBUG
        uc client = new UdpClient(34534);
    #else
        uc client = new UdpClient();
    #endif
    

    UdpClient Constructor (Int32)

    Initializes a new instance of the UdpClient class and binds it to the local port number provided.

    Remarks

    This constructor creates an underlying Socket and binds it to the port number from which you intend to communicate. Use this constructor if you are only interested in setting the local port number. The underlying service provider will assign the local IP address. If you pass 0 to the constructor, the underlying service provider will assign a port number. If this constructor is used, the UdpClient instance is set with an address family of IPv4 that cannot be changed or overwritten by a connect method call with an IPv6 target.

    Disclaimer, totally untested, just read the documentation, possibly wrong :)