在C#中调用API获取网络信息和流量

在C#中调用API获取网络信息和流量

最近一项目中要求显示网络流量,而且必须使用C#。

事实上,调用 IpHlpApi.dll 的 GetIfTable API 可以轻易获得网络信息和网络流量。只是要在C#中实现还是比较复杂。

先看看怎么定义该 API

[DllImport( " IpHlpApi.dll " )]
        
extern   static   public   uint  GetIfTable( byte [] pIfTable,  ref   uint  pdwSize,  bool  bOrder);

本来想把 pIfTable 定义为 IntPtr,但是这样的结果是,获取的信息是错误的(直到现在都不知是什么原因)。

但显然定义为 byte[] 是不能直接使用的。幸好在 Google Code Search 找到了三个类:


using System;
using System.IO;
using System.Collections;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;

namespace Lemony.SystemInfo
{
    
    
/// <summary>
    
/// CustomMarshaler class implementation.
    
/// </summary>

    public abstract class CustomMarshaler
    
{
        
#region Fields
        
// The internal buffer
        internal byte[] data;
        
private MemoryStream stream;
        
private BinaryReader binReader;
        
private BinaryWriter binWriter;
        
        
#endregion

    
        
constructors

        
public methods

        
properties

        
virtual and protected methods

        
helper methods

    }


    
MarshallingMethods class

    
CustomMarshalAsAttribute

}


MIB_IFROW.cs

MIB_IFTABLE.cs

再定义一个 NetInfo 类,存储网络信息

NetInfo.cs

OK,现在可以获取网络信息了

         /// <summary>
        
/// Get IFTable
        
/// </summary>
        
/// <returns>MIB_IFTABLE Class</returns>

         private   static  MIB_IFTABLE GetAllIfTable()
        
{
            
//缓冲区大小
            uint dwSize = 0;

            
//获取缓冲区大小
            uint ret = GetIfTable(nullref dwSize, false);
            
if (ret == 50)
            
{
                
//此函数仅支持于 win98/nt 系统
                return null;
            }


            
//定义,获取 MIB_IFTABLE 对象
            MIB_IFTABLE tbl = new MIB_IFTABLE((int)dwSize);
            ret 
= GetIfTable(tbl.ByteArray, ref dwSize, false);

            
//如果不成功
            if (ret != 0)
            
{
                
return null;
            }


            
return tbl;
        }


        
/**/
         private   static  NetInfo GetNetInfo(MIB_IFROW row)
        

/**/
         public   static  List < NetInfo >  GetAllNetInfo()
        
{
            
//定义范型
            List<NetInfo> ninfos = new List<NetInfo>();

            
//定义,获取 MIB_IFTABLE 对象
            MIB_IFTABLE tbl = GetAllIfTable();

            
//如果成功
            if (tbl != null)
            
{
                tbl.Deserialize();
                
for (int i = 0; i < tbl.Table.Length; i++)
                
{
                    ninfos.Add(GetNetInfo(tbl.Table[i]));
                }

            }


            
return ninfos;
        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值