如何仅 Ping IPv4?
How to Ping for IPv4 only?
我知道路由器的 IPv4 地址。但是当我使用 TTL = 1 Ping 时,我没有得到那个 IP。相反,我得到了它的 IPv6 地址。 (我知道 address.MapToIPv4()
但那仅适用于已更改为 IPv6 的 IPv4。)
那么如何仅 ping IPv4(如 tracert's /4 switch)?
var reply = new Ping().Send("example.com", 10000, new byte[] { 1 }, new PingOptions(1, true));
查看源代码(Reference Source, GitHub), if the parameter passed to Send()
is a name then Dns.GetHostAddresses()
用于解析它,返回的第一个地址就是所使用的地址。因此,如果第一个地址是 IPv6 地址,那么该地址将被 ping 并且有无法改变这种行为。
相反,您可以调用 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...
}
我知道路由器的 IPv4 地址。但是当我使用 TTL = 1 Ping 时,我没有得到那个 IP。相反,我得到了它的 IPv6 地址。 (我知道 address.MapToIPv4()
但那仅适用于已更改为 IPv6 的 IPv4。)
那么如何仅 ping IPv4(如 tracert's /4 switch)?
var reply = new Ping().Send("example.com", 10000, new byte[] { 1 }, new PingOptions(1, true));
查看源代码(Reference Source, GitHub), if the parameter passed to Send()
is a name then Dns.GetHostAddresses()
用于解析它,返回的第一个地址就是所使用的地址。因此,如果第一个地址是 IPv6 地址,那么该地址将被 ping 并且有无法改变这种行为。
相反,您可以调用 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...
}