You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Binding with ReuseAddress not working with UdpClient on Linux #27274
Binding multiple clients on Linux platform in dotnet framework 2.1 does not work as expected
I am binding to a socket with SO_REUSEADDR (MultiCastClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);) but on Linux this gives me an address already in use exception.
In dotnet core 2.0 this was working fine.
General
I have the following relevant piece of code:
...MultiCastClient=newUdpClient();MultiCastClient.Client.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReuseAddress,true);varEndPoint=newIPEndPoint(IPAddress.Any,_listenPort);MultiCastClient.JoinMulticastGroup(IPAddress.Parse(multicastAddress));MultiCastClient.Client.Bind(EndPoint);// <--- this is where the bind exception happens.try{MultiCastClient.BeginReceive(RecieveCallBack,null);}...
I have a project targeting netcoreapp2.0
When I am running this with dotnet-hosting-2.0.8 everything is fine. However when I am running this with the newer CLR aspnetcore-runtime-2.1 (all on Debian 9) I am getting a bind exception:
Application startup exception: System.Net.Sockets.SocketException (98): Address already in use
at System.Net.Sockets.Socket.UpdateStatusAfterSocketErrorAndThrowException(SocketError error, String callerName)
at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.Sockets.Socket.Bind(EndPoint localEP)
at UDPNMEAMessageReciever.UdpMessageProcessor.Start()
...
I havent looked into it much further, but I would like to be able to use the newer CLR.
Thanks for helping me out here, I really appreciate your efforts.
Hi Tom,
Tnx for looking into this. I'm running socat and another java client all on the same binding.
I haven't tried running multiple instances but will try tomorrow.
Hope this helps
Hi @tmds ,
I see you've already figured out how to reproduce this and have pushed a fix to mitigate my issue. Can you give me an indication when I can expect this into the regular release? I'm very happy with how fast you've resolved this. Thank you.
@karelz when the PR is merged on master, will it become part of the 2.2 release? Can we consider this for 2.1?
@olijf by adding the setsockopt(s.Handle.ToInt32(), 1, 2, &value, sizeof(int)); you should be able to unblock yourself. Please give it a try, an confirm that resolves the issue.
peudo code:
UdpClientMultiCastClient=newUdpClient();MultiCastClient.Client.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReuseAddress,true);if(RuntimeInformation.IsOSPlatform(OSPlatform.Linux)){// set SO_REUSEADDR (https://github.com/dotnet/corefx/issues/32027)intvalue=1;setsockopt(MultiCastClient.Client.Handle.ToInt32(),1,2,&value,sizeof(int));}[DllImport("libc",SetLastError=true)]privateunsafestaticexternintsetsockopt(intsocket,intlevel,intoption_name,void*option_value,uintoption_len);
@olijf When setting both SO_REUSEADDR (via setsockopt) and SO_REUSEPORT (via SocketOptionName.ReuseAddress), I only got a bind exception when a previous socket was bound that didn't set any option.
@tmds master flows into 3.0. 2.2 is almost-servicing bar. Can you sum up the impact of this problem? If it is wide-impact, or if there is not a good workaround, we could consider it for 2.2 or 2.1.x.
Hi @karelz , imho I think this is actually a pretty big issue. Because you can not distinguish between SO_REUSEPORT and SO_REUSEADDR in dotnet core this is a major problem if you have multiple clients running created in different programming languages on the same binding (which all have different ways of doing the same thing). Plus it's a regression compared to the previous 2.0 runtime. I hope my opinion helps to decide what's best.
I'm experiencing a similar issue.
I have a custom Azure IoT Edge module which runs in a Linux container. The IoT Edge module uses the Zeroconf library to discover devices in the network via mDNS. ZeroConf uses UdpClient to bind to a certain socket. When the IoT Edge module starts, ZeroConf is called to discover the devices.
I get the following exception:
<06/04/201910:03:23>Address already in use
<06/04/201910:03:23>at System.Net.Sockets.Socket.UpdateStatusAfterSocketErrorAndThrowException(SocketErrorerror,StringcallerName)
at System.Net.Sockets.Socket.DoBind(EndPointendPointSnapshot,SocketAddresssocketAddress)
at System.Net.Sockets.Socket.Bind(EndPointlocalEP)
at Zeroconf.NetworkInterface.NetworkRequestAsync(Byte[]requestBytes,TimeSpanscanTime,Int32retries,Int32retryDelayMilliseconds, Action`2onResponse,NetworkInterfaceadapter,CancellationTokencancellationToken)inD:\a\1\s\Zeroconf\NetworkInterface.cs:line 107
at Zeroconf.NetworkInterface.NetworkRequestAsync(Byte[]requestBytes,TimeSpanscanTime,Int32retries,Int32retryDelayMilliseconds, Action`2onResponse,NetworkInterfaceadapter,CancellationTokencancellationToken)inD:\a\1\s\Zeroconf\NetworkInterface.cs:line 169
at Zeroconf.NetworkInterface.NetworkRequestAsync(Byte[]requestBytes,TimeSpanscanTime,Int32retries,Int32retryDelayMilliseconds, Action`2onResponse,CancellationTokencancellationToken)inD:\a\1\s\Zeroconf\NetworkInterface.cs:line 34
at Zeroconf.ZeroconfResolver.ResolveInternal(ZeroconfOptionsoptions, Action`2callback,CancellationTokencancellationToken)inD:\a\1\s\Zeroconf\ZeroconfResolver.cs:line 79
at Zeroconf.ZeroconfResolver.ResolveAsync(ResolveOptionsoptions, Action`1callback,CancellationTokencancellationToken)inD:\a\1\s\Zeroconf\ZeroconfResolver.Async.cs:line 98
at Zeroconf.ZeroconfResolver.ResolveAsync(IEnumerable`1protocols,TimeSpanscanTime,Int32retries,Int32retryDelayMilliseconds, Action`1callback,CancellationTokencancellationToken)inD:\a\1\s\Zeroconf\ZeroconfResolver.Async.cs:line 69
When I look into the relevant ZeroConf code, I notice that UdpClient is used and that
using(varclient=newUdpClient()){for(vari=0;i<retries;i++){try{varsocket=client.Client;if(socket.IsBound)continue;socket.SetSocketOption(SocketOptionLevel.IP,SocketOptionName.MulticastInterface,IPAddress.HostToNetworkOrder(ifaceIndex));client.ExclusiveAddressUse=false;socket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReuseAddress,true);socket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReceiveTimeout,(int)scanTime.TotalMilliseconds);client.ExclusiveAddressUse=false;varlocalEp=newIPEndPoint(IPAddress.Any,5353);Debug.WriteLine($"Attempting to bind to {localEp} on adapter {adapter.Name}");socket.Bind(localEp);
(The exception is thrown on the socket.Bind() call).
if(RuntimeInformation.IsOSPlatform(OSPlatform.Linux)){// set SO_REUSEADDR (https://github.com/dotnet/corefx/issues/32027)intvalue=1;setsockopt(MultiCastClient.Client.Handle.ToInt32(),1,2,&value,sizeof(int));}[DllImport("libc",SetLastError=true)]privateunsafestaticexternintsetsockopt(intsocket,intlevel,intoption_name,void*option_value,uintoption_len);
if(RuntimeInformation.IsOSPlatform(OSPlatform.Linux)){// set SO_REUSEADDR (https://github.com/dotnet/corefx/issues/32027)intvalue=1;setsockopt(MultiCastClient.Client.Handle.ToInt32(),1,2,&value,sizeof(int));}[DllImport("libc",SetLastError=true)]privateunsafestaticexternintsetsockopt(intsocket,intlevel,intoption_name,void*option_value,uintoption_len);
We had the same problem and I can confirm that this has fixed it for us.
I'm not sure this is related to this issue, so if need by, I'll start another. I have observed what I think is a discrepency in how .net core handles sockets compared to native (on linux, at least)
I am talking about the case where two sockets are bound to the same endpoint, but only one is connected to a remote endpoint. I have an SO question on the subject, and it seems that the behaviour is "undefned", yet the code here works perfectly, and does exactly that.
Specifically, the code I linked creates 2 sockets, one to listen for incoming dtls "connection" requests, and another for a connected client. Both of these sockets are bound to the same endpoint, and the second is connected to the client's endpoint. The result is that all traffic originating from the "connected" client is forwarded to the socket created specifically for them, and all other traffic is forwarded to the unconnected socket.
I tried to replicate this behaviour in C# with no luck. As I mentioned, it seems that in this specific case, the behavior is undefined and the data seems to be forwarded to a socket at random.
My code is as follows:
var localEp = new IPEndPoint(IPAddress.Loopback, 1114);
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
socket.Bind(localEp);
...
Setting up SSL
...
var clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
clientSocket.Bind(localEp);
clientSocket.Connect(bioAddr);
At this point, there is no way to guarantee that the client's dgrams will make it to clientSocket. This does not match the behavior of the code I linked above.
Is this a bug in .net? I am using .net core 3.0, so I know that both SO_REUSEADDRESS and SO_REUSEPORT are being set. I'm not sure what I am missing...
Yes you are correct. My code doesn't work in both dotnet core 2.2 (where SO_REUSEPORT is not set) and 3.0 (where it is). So it seems that SO_REUSEPORT has no effect on the result.
The bottom line is that the behavior I described is achievable in native code, but there seems to be no way in dotnet.
Activity
tmds commentedon Aug 30, 2018
This may be caused by changes in dotnet/corefx#24809.
With 2.0 ReuseAddress did:
With 2.1 it does:
I'm trying to reproduce this, but I'm missing something. I can run two instances of this program concurrently:
tmds commentedon Aug 30, 2018
@olijf does this happen with two instances of your own program? Or is another program also using the port?
olijf commentedon Aug 30, 2018
Hi Tom,
Tnx for looking into this. I'm running
socatand another java client all on the same binding.I haven't tried running multiple instances but will try tomorrow.
Hope this helps
tmds commentedon Aug 30, 2018
I can reproduce this. The issue occurs when two applications each use a different option: one does
SO_REUSEADDRand the otherSO_REUSEPORT.The fix will be to change back to changing both options for
SocketOptionName.ReuseAddress.@davidsh you can assign this to me.
olijf commentedon Sep 3, 2018
Hi @tmds ,
I see you've already figured out how to reproduce this and have pushed a fix to mitigate my issue. Can you give me an indication when I can expect this into the regular release? I'm very happy with how fast you've resolved this. Thank you.
tmds commentedon Sep 3, 2018
@karelz when the PR is merged on master, will it become part of the 2.2 release? Can we consider this for 2.1?
@olijf by adding the
setsockopt(s.Handle.ToInt32(), 1, 2, &value, sizeof(int));you should be able to unblock yourself. Please give it a try, an confirm that resolves the issue.peudo code:
olijf commentedon Sep 3, 2018
@tmds Your workaround works fine in one scenario but in another one i'm still getting the bind exception. I'm still investigation why this happens.
tmds commentedon Sep 4, 2018
@olijf When setting both SO_REUSEADDR (via setsockopt) and SO_REUSEPORT (via SocketOptionName.ReuseAddress), I only got a bind exception when a previous socket was bound that didn't set any option.
karelz commentedon Sep 4, 2018
@tmds master flows into 3.0. 2.2 is almost-servicing bar. Can you sum up the impact of this problem? If it is wide-impact, or if there is not a good workaround, we could consider it for 2.2 or 2.1.x.
karelz commentedon Sep 4, 2018
Based on reviewing the PR in master, it seems to be rather rare corner case, right?
Plus the workaround, sounds reasonably (although kind of ugly).
Given that we have only 1 report so far, I recommend to NOT port it to 2.2/2.1.x, until we get more developers hitting the problem.
olijf commentedon Sep 4, 2018
Hi @karelz , imho I think this is actually a pretty big issue. Because you can not distinguish between
SO_REUSEPORTandSO_REUSEADDRin dotnet core this is a major problem if you have multiple clients running created in different programming languages on the same binding (which all have different ways of doing the same thing). Plus it's a regression compared to the previous 2.0 runtime. I hope my opinion helps to decide what's best.karelz commentedon Sep 4, 2018
@olijf the key question is: How common is such setup?
I understand that if someone needs it, then it is bad, although there is a workaround.
tmds commentedon Sep 7, 2018
@olijf have you found the reason for the exception?
tmds commentedon Oct 9, 2018
This issue is fixed by dotnet/corefx#32046
15 remaining items
fgheysels commentedon Jun 4, 2019
I'm experiencing a similar issue.
I have a custom Azure IoT Edge module which runs in a Linux container. The IoT Edge module uses the Zeroconf library to discover devices in the network via mDNS. ZeroConf uses UdpClient to bind to a certain socket. When the IoT Edge module starts, ZeroConf is called to discover the devices.
I get the following exception:
When I look into the relevant ZeroConf code, I notice that
UdpClientis used and that(The exception is thrown on the
socket.Bind()call).matthew798 commentedon Sep 4, 2019
Was this ever backported to 2.2/2.1?
davidsh commentedon Sep 4, 2019
It was not. There are no plans to backport it. In generally, not all fixes get backported to previous releases.
davidsh commentedon Sep 4, 2019
Check out the latest .NET Core 3.0 preview. It is suitable for 'go-live' scenarios:
https://devblogs.microsoft.com/dotnet/announcing-net-core-3-0-preview-9/
matthew798 commentedon Sep 4, 2019
@davidsh Thanks, was hoping to not have to use the workaround. I am writing a library, users could be on any version.
QTimort commentedon Sep 4, 2019
@matthew798 Not sure if this can help you but I posted a hack that works, it was tested on .NET Core 2.1. It could be improved, see https://github.com/QTimort/bind-reuse-port
matthew798 commentedon Sep 4, 2019
@QTimort Thanks. I'll have a look!
tmds commentedon Sep 5, 2019
Alternatively, you can us the code from https://github.com/dotnet/corefx/issues/32027#issuecomment-417395637
softworkz commentedon Sep 5, 2019
We had the same problem and I can confirm that this has fixed it for us.
matthew798 commentedon Sep 5, 2019
I'm not sure this is related to this issue, so if need by, I'll start another. I have observed what I think is a discrepency in how .net core handles sockets compared to native (on linux, at least)
I am talking about the case where two sockets are bound to the same endpoint, but only one is connected to a remote endpoint. I have an SO question on the subject, and it seems that the behaviour is "undefned", yet the code here works perfectly, and does exactly that.
Specifically, the code I linked creates 2 sockets, one to listen for incoming dtls "connection" requests, and another for a connected client. Both of these sockets are bound to the same endpoint, and the second is connected to the client's endpoint. The result is that all traffic originating from the "connected" client is forwarded to the socket created specifically for them, and all other traffic is forwarded to the unconnected socket.
I tried to replicate this behaviour in C# with no luck. As I mentioned, it seems that in this specific case, the behavior is undefined and the data seems to be forwarded to a socket at random.
My code is as follows:
At this point, there is no way to guarantee that the client's dgrams will make it to
clientSocket. This does not match the behavior of the code I linked above.Is this a bug in .net? I am using .net core 3.0, so I know that both SO_REUSEADDRESS and SO_REUSEPORT are being set. I'm not sure what I am missing...
tmds commentedon Sep 6, 2019
In the code you linked to: SO_REUSEPORT is not set on Linux: https://github.com/nplab/DTLS-Examples/blob/226f222e528858b3a8c5fa3326b0599d25d3ef1c/src/dtls_udp_echo.c#L652-L654
matthew798 commentedon Sep 6, 2019
Yes you are correct. My code doesn't work in both dotnet core 2.2 (where SO_REUSEPORT is not set) and 3.0 (where it is). So it seems that SO_REUSEPORT has no effect on the result.
The bottom line is that the behavior I described is achievable in native code, but there seems to be no way in dotnet.
Ill open another issue.