J4N
J4N

Reputation: 20737

UdpClient: Specify the source port when sending a data

I'm using UdpClient to send data on multicast address.

The code looks like this:

m_udpclientSender = new UdpClient();
m_remoteEndPoint = new IPEndPoint(m_multicastAddress, m_port);
m_udpclientSender.ExclusiveAddressUse = false;
m_udpclientSender.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
m_udpclientSender.JoinMulticastGroup(m_multicastAddress, 255);
m_udpclientSender.ExclusiveAddressUse = false;
m_udpclientSender.Send(buffer, buffer.Length, m_remoteEndPoint);

It is sent to the correct port/ip, but it issued from a random port(which is expected), but I need/want this to be sent from a specific port(the same port that I'm sending too).

I saw that: How to specify source port of a UdpPacket?

But I need to NOT exclusively use address, and if I give this in the constructor, I got an exception(saying that this is already bound).

I've to put the same port because the protocol defines that the response should not be multicasted.

Upvotes: 1

Views: 3754

Answers (2)

J4N
J4N

Reputation: 20737

In fact, according to the documentation:

This property must be set before the underlying socket is bound to a client port. If you call UdpClient.UdpClient(Int32), UdpClient.UdpClient(Int32, AddressFamily), UdpClient.UdpClient(IPEndPoint), or UdpClient.UdpClient(String, Int32), the client port is bound as a side effect of the constructor, and you cannot subsequently set the ExclusiveAddressUse property

So it's impossible to set the ExclusiveAddressUse to false when setting the source port. I used the Socket directly

Upvotes: 0

David Pfeffer
David Pfeffer

Reputation: 39833

You've done everything correct, but it sounds like the other user of the port already has exclusive port access. WinSock will not let you send from this port.

Upvotes: 1

Related Questions