C# 网络接口速度

C# 网络接口速度,c#,windows-xp,C#,Windows Xp,我想获取我的网络接口的名称、速度和MAC地址 var searcher = new ManagementObjectSearcher { Scope = GetConnectedScope(target, "cimv2") }; try { searcher.Query = new ObjectQuery("SELECT MACAddress, Speed, Name FROM Win32_NetworkAdapter");

我想获取我的网络接口的名称、速度和MAC地址

    var searcher = new ManagementObjectSearcher { Scope = GetConnectedScope(target, "cimv2") };

        try
        {
           searcher.Query = new ObjectQuery("SELECT MACAddress, Speed, Name FROM Win32_NetworkAdapter");

            var nicList = new List<NetworkInterfaceModel>();
            foreach (var item in searcher.Get())
            {
                nicList.Add(new NetworkInterfaceModel
                {
                    NetworkInterfaceName = (string)item["Name"],
                    NetworkInterfaceSpeed = (double)(item["Speed"] != null ? (ulong) item["Speed"] : 0)/1000/1000,
                    MacAddress = (string)item["MACAddress"]
                });
            }
var searcher=newmanagementobjectsearcher{Scope=GetConnectedScope(目标,“cimv2”)};
尝试
{
Query=newObjectQuery(“从Win32_NetworkAdapter中选择MACAddress、Speed、Name”);
var nicList=新列表();
foreach(searcher.Get()中的var项)
{
nicList.Add(新的网络接口模型)
{
NetworkInterfaceName=(字符串)项[“名称”],
NetworkInterfaceSpeed=(双精度)(项目[“速度”]!=null?(ulong)项目[“速度”]:0)/1000/1000,
MacAddress=(字符串)项[“MacAddress”]
});
}

对于Windows 7和Vista,它工作正常,但是对于XP和Windows Server 2003,它没有收集到速度。如何获得XP和Server 2003的速度?

Win32\u NetworkAdapter
不支持XP下的
speed
属性,如下所示:

Windows Server 2003、Windows XP、Windows 2000和Windows NT 4.0:此属性尚未实现。默认情况下,它返回空值

相反,使用具有相同属性的
CIM\u NetworkAdapter


您可以使用windows cmd获取网络名称:

Process p = new Process();
p.StartInfo.FileName = "netsh.exe";
p.StartInfo.Arguments = "wlan show interfaces";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
string s = p.StandardOutput.ReadToEnd();
string s1 = s.Substring(s.IndexOf("SSID"));
s1 = s1.Substring(s1.IndexOf(":"));
s1 = s1.Substring(2, s1.IndexOf("\n")).Trim();
p.WaitForExit();

namelabel.Text = s1;
对于MAC地址:

 IPAddress IP = IPAddress.Parse("192.168.1.1");
 byte[] macAddr = new byte[6];
 uint macAddrLen = (uint)macAddr.Length;
 UInt32 nRet = 0;
 uint nAddress = BitConverter.ToUInt32(IP.GetAddressBytes(), 0);
 nRet = SendARP(nAddress, 0, macAddr, ref macAddrLen);
 if (nRet == 0)
 {
     string[] sMacAddress = new string[(int)macAddrLen];

     for (int i = 0; i < macAddrLen; i++)
     {
         sMacAddress[i] = macAddr[i].ToString("x2");
         string macAddress += sMacAddress[i] + (i < macAddrLen - 1 ? ":" : "");

     }
 }
首先添加TimerInterval(您希望以多快的速度更改为新值)、NetworkInterface和计时器:

private const double timerUpdate = 1000;
private NetworkInterface[] nicArr;
private Timer timer;
然后在启动时继续使用以下组件:

public Form1()
    {
        InitializeComponent();
        InitializeNetworkInterface();
        InitializeTimer();
    }
组件:

private void InitializeNetworkInterface()
{
    // Grab all local interfaces to this computer
    nicArr = NetworkInterface.GetAllNetworkInterfaces();

    // Add each interface name to the combo box
    for (int i = 0; i < nicArr.Length; i++)
        comboBox1.Items.Add(nicArr[i].Name); //you add here the interface types in a combobox and select from here WiFi, ethernet etc...

    // Change the initial selection to the first interface
    comboBox1.SelectedIndex = 0;
}
private void InitializeTimer()
{
     timer = new Timer();
     timer.Interval = (int)timerUpdate;
     timer.Tick += new EventHandler(timer_Tick);
     timer.Start();
 }
使用此空,您将更新ping:

public void UpdatePing()
{     
    try
    {
        Ping myPing = new Ping();
        PingReply reply = myPing.Send(textBox1.Text, 1000);
        if (reply != null)
        {
            label17.Text = reply.Status.ToString();
            label18.Text = reply.RoundtripTime.ToString();                    
        }
    }
    catch
    {
        label17.Text = "ERROR: You have Some TIMEOUT issue";
        label18.Text = "ERROR: You have Some TIMEOUT issue";                
    }
}
最后用这个以网络形式显示速度:

private void UpdateNetworkInterface()
{
    // Grab NetworkInterface object that describes the current interface
    NetworkInterface nic = nicArr[comboBox1.SelectedIndex];

    // Grab the stats for that interface
    IPv4InterfaceStatistics interfaceStats = nic.GetIPv4Statistics();

    // Calculate the speed of bytes going in and out
    // NOTE: we could use something faster and more reliable than Windows Forms Tiemr
    //       such as HighPerformanceTimer http://www.m0interactive.com/archives/2006/12/21/high_resolution_timer_in_net_2_0.html

    // Update the labels
    speedlbl.Text = nic.Speed.ToString();
    interfaceTypelbl.Text = nic.NetworkInterfaceType.ToString();            
    bytesReceivedlbl.Text = interfaceStats.BytesReceived.ToString();
    bytesSentlbl.Text = interfaceStats.BytesSent.ToString();

    int bytesSentSpeed = (int)(interfaceStats.BytesSent - double.Parse(label10.Text)) / 1024;
    int bytesReceivedSpeed = (int)(interfaceStats.BytesReceived - double.Parse(label11.Text)) / 1024;

    bytescomelbl.Text = bytesSentSpeed.ToString() + " KB/s";
    bytessentlbl.Text = bytesReceivedSpeed.ToString() + " KB/s";

}

如果您想支持Windows的旧版本,那么您可能不太可能通过WMI来实现。然后,您可能会建议如何在没有WMI的情况下实现这一点
void timer_Tick(object sender, EventArgs e)
{
    UpdateNetworkInterface();                
}
public void UpdatePing()
{     
    try
    {
        Ping myPing = new Ping();
        PingReply reply = myPing.Send(textBox1.Text, 1000);
        if (reply != null)
        {
            label17.Text = reply.Status.ToString();
            label18.Text = reply.RoundtripTime.ToString();                    
        }
    }
    catch
    {
        label17.Text = "ERROR: You have Some TIMEOUT issue";
        label18.Text = "ERROR: You have Some TIMEOUT issue";                
    }
}
private void UpdateNetworkInterface()
{
    // Grab NetworkInterface object that describes the current interface
    NetworkInterface nic = nicArr[comboBox1.SelectedIndex];

    // Grab the stats for that interface
    IPv4InterfaceStatistics interfaceStats = nic.GetIPv4Statistics();

    // Calculate the speed of bytes going in and out
    // NOTE: we could use something faster and more reliable than Windows Forms Tiemr
    //       such as HighPerformanceTimer http://www.m0interactive.com/archives/2006/12/21/high_resolution_timer_in_net_2_0.html

    // Update the labels
    speedlbl.Text = nic.Speed.ToString();
    interfaceTypelbl.Text = nic.NetworkInterfaceType.ToString();            
    bytesReceivedlbl.Text = interfaceStats.BytesReceived.ToString();
    bytesSentlbl.Text = interfaceStats.BytesSent.ToString();

    int bytesSentSpeed = (int)(interfaceStats.BytesSent - double.Parse(label10.Text)) / 1024;
    int bytesReceivedSpeed = (int)(interfaceStats.BytesReceived - double.Parse(label11.Text)) / 1024;

    bytescomelbl.Text = bytesSentSpeed.ToString() + " KB/s";
    bytessentlbl.Text = bytesReceivedSpeed.ToString() + " KB/s";

}