Skip to content

Commit

Permalink
avoid processing incorrect ICMP message on Unix (dotnet/corefx#34084)
Browse files Browse the repository at this point in the history
* use connect on unicast ping addresses to avoild processing incorrect responses

* feedback from review


Commit migrated from dotnet/corefx@3172386
  • Loading branch information
wfurt committed Dec 19, 2018
1 parent 158c3fd commit c6efaf4
Showing 1 changed file with 15 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -88,15 +88,28 @@ private SocketConfig GetSocketConfig(IPAddress address, byte[] buffer, int timeo

private Socket GetRawSocket(SocketConfig socketConfig)
{
IPEndPoint ep = (IPEndPoint)socketConfig.EndPoint;

// Setting Socket.DontFragment and .Ttl is not supported on Unix, so socketConfig.Options is ignored.
AddressFamily addrFamily = ((IPEndPoint)socketConfig.EndPoint).Address.AddressFamily;
AddressFamily addrFamily = ep.Address.AddressFamily;
Socket socket = new Socket(addrFamily, SocketType.Raw, socketConfig.ProtocolType);
socket.ReceiveTimeout = socketConfig.Timeout;
socket.SendTimeout = socketConfig.Timeout;
if (socketConfig.Options != null && socketConfig.Options.Ttl > 0)
{
socket.Ttl = (short)socketConfig.Options.Ttl;
}

#pragma warning disable 618
// Disable warning about obsolete property. We could use GetAddressBytes but that allocates.
// IPv4 multicast address starts with 1110 bits so mask rest and test if we get correct value e.g. 0xe0.
if (!ep.Address.IsIPv6Multicast && !(addrFamily == AddressFamily.InterNetwork && (ep.Address.Address & 0xf0) == 0xe0))
{
// If it is not multicast, use Connect to scope responses only to the target address.
socket.Connect(socketConfig.EndPoint);
}
#pragma warning restore 618

return socket;
}

Expand Down Expand Up @@ -129,7 +142,7 @@ private bool TryGetPingReply(SocketConfig socketConfig, byte[] receiveBuffer, in
{
return false;
}

sw.Stop();
long roundTripTime = sw.ElapsedMilliseconds;
int dataOffset = ipHeaderLength + IcmpHeaderLengthInBytes;
Expand Down

0 comments on commit c6efaf4

Please sign in to comment.