目前写个小程式电脑多张网卡,确认到底是哪张网卡ping出去的.
比如远端ip:192.168.24.224,本机ip:192.168.24.130。Cmd指令:C:>ping 192.168.24.224 -S 192.168.24.130
用C# ping类如何实现?
使用tracert命令
https://jingyan.baidu.com/article/9c69d48f4df25713c8024e66.html
ping -S 192.168.24.130 192.168.24.224
S是大写,IP先是本机IP,后是目标IP
问题使用Process的方式解决了,但结果不是很满意,代码以下,
如有通过C# Ping类完成的大神请分享您的成果.
public bool PingFunction(string remoteIp, string localIp, ListBox r)
{
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";//设定程序名
p.StartInfo.UseShellExecute = false; //关闭Shell的使用
p.StartInfo.RedirectStandardInput = true;//重定向标准输入
p.StartInfo.RedirectStandardOutput = true;//重定向标准输出
p.StartInfo.RedirectStandardError = true;//重定向错误输出
p.StartInfo.CreateNoWindow = true;//设置不显示窗口
p.Start();
p.StandardInput.WriteLine("chcp 437"); //让Cmd中显示英文
p.StandardInput.WriteLine("arp -d\r\narp -d\r\narp -d\r\n");
p.StandardInput.WriteLine("ping " + remoteIp + " -S " + localIp);
p.StandardInput.WriteLine("exit");
string strRst = p.StandardOutput.ReadToEnd();
p.Close();
bool isOk = false;
string temp = "";
if (strRst.Contains("(0% loss)") || strRst.Contains("(0% 丢失)"))
{
strRst = strRst.Substring(strRst.IndexOf("Reply from", StringComparison.Ordinal));
temp = strRst.Substring(0, strRst.IndexOf("\r\n", StringComparison.Ordinal));
isOk = true;
}
else if (strRst.Contains("Destination host unreachable."))
{
temp = "Destination host unreachable.";
}
else if (strRst.Contains("Request timed out."))
{
temp = "Request timed out.";
}
else if (strRst.Contains("Unknown host"))
{
temp = "Unknown host.";
}
else
{
temp = "Unknown Error.";
}
r.Invoke(new Action(() =>
{
r.Items.Add(temp + Environment.NewLine);
r.ForeColor = Color.Green;
}));
return isOk;
}
//Ping 实例对象;
Ping pingSender = new Ping();
//ping选项;
PingOptions options = new PingOptions();
options.DontFragment = true;
string data = "ping test data";
byte[] buf = Encoding.ASCII.GetBytes(data);
//调用同步send方法发送数据,结果存入reply对象;
PingReply reply = pingSender.Send("www.baidu.com", 120, buf, options);