I know my router's IPv4 address. But when I Ping using TTL = 1 I don't get that IP. Rather, I get its IPv6 address. (I know of address.MapToIPv4()
but that's only for IPv4s that were changed into IPv6s.)
So how do I ping for IPv4 only (like tracert's /4 switch)?
var reply = new Ping().Send("example.com", 10000, new byte[] { 1 }, new PingOptions(1, true));
Looking at the source code (Reference Source, GitHub), if the parameter passed to Send()
is a name then Dns.GetHostAddresses()
is used to resolve it and the first address returned is what's used. Thus, if that first address is an IPv6 address then that address is what will be pinged and there's no way to change that behavior.
Instead, you could call Dns.GetHostAddresses()
yourself, filter the results to include or prefer IPv4 addresses, and pass that to Ping.Send()
:
IPAddress addressToPing = Dns.GetHostAddresses("example.com")
.First(address => address.AddressFamily == AddressFamily.InterNetwork);
using (Ping ping = new Ping())
{
PingReply reply = ping.Send(addressToPing, 10000, new byte[] { 1 }, new PingOptions(1, true));
// Do something with reply...
}