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

来源:http://www.chinese-glasses.com 作者:Web前端 人气:114 发布时间:2020-03-31
摘要:时间: 2019-10-21阅读: 70标签: 转换             // Get all public fields             FieldInfo[] fields =this.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance);                    

时间: 2019-10-21阅读: 70标签: 转换

            // Get all public fields
            FieldInfo[] fields = this.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance);
           
            // Loop through the fields
            foreach(FieldInfo field in fields)
            {
                // Retrieve the read method from ReadMethods hashtable
                MethodInfo method = (MethodInfo)MarshallingMethods.ReadMethods[field.FieldType];

1、uint8Array转string

        private uint m_OutErrors;
        /**////
        /// 总错发字节数
        ///
        public uint OutErrors
        {
            get { return m_OutErrors; }
            set { m_OutErrors = value; }
        }

function arrayBufferToString(buf) { return String.fromCharCode.apply(null, new Uint8Array(buf));}

            FieldInfo[] fields = this.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance);

function intTobytes(n) { var bytes = []; for (var i = 0; i  2; i++) { bytes[i] = n  (8 - i * 8); } return bytes;}intTobytes(10) // [0, 10]

        private uint m_InOctets;
        /**////
        /// 总接收字节数
        ///
        public uint InOctets
        {
            get { return m_InOctets; }
            set { m_InOctets = value; }
        }

function base64toBlob(base64,type) { // 将base64转为Unicode规则编码 bstr = atob(base64, type), n = bstr.length, u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n) // 转换编码后才可以使用charCodeAt 找到Unicode编码 } return new Blob([u8arr], { type, })} 输出:Blob {size: 3, type: "png"}

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

6、base64转blob(二进制)

        public static uint[] ReadUInt32Array(BinaryReader reader, int count)
        {
            uint[] result = new uint[count];

3、int转byte[]

        public MIB_IFTABLE(int size)
        {
            this.data = new byte[size];
        }
    }
}

2、string装uint8Array

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

4、string转ArrayBuffer

}

function stringToUint8Array(str){ var arr = []; for (var i = 0, j = str.length; i  j; ++i) { arr.push(str.charCodeAt(i)); } var tmpUint8Array = new Uint8Array(arr); return tmpUint8Array}stringToUint8Array('12313132') // Uint8Array(8) [49, 50, 51, 49, 51, 49, 51, 50]

    }

5、arrayBuffer转string

        public MIB_IFTABLE()
        {
            this.data = new byte[this.GetSize()];
        }

function stringToArrayBuffer(str) { var buf = new ArrayBuffer(str.length * 2); // 每个字符占用2个字节 var bufView = new Uint16Array(buf); for (var i = 0, strLen = str.length; i  strLen; i++) { bufView[i] = str.charCodeAt(i); } return buf;}stringToArrayBuffer('00000')输出:ArrayBuffer(10) {}

        public static void WriteSerializers(BinaryWriter writer, CustomMarshaler[] arr)
        {
            for (int i = 0; i < arr.Length; i++)
            {
                arr[i].WriteToStream(writer);
            }
        }

function uint8ArrayToString(fileData){ var dataString = ""; for (var i = 0; i  fileData.length; i++) { dataString += String.fromCharCode(fileData[i]); } return dataString}var arr = [48,48,48,48]uint8ArrayToString(arr) //"0000"

        }

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

    CustomMarshalAsAttribute#region CustomMarshalAsAttribute
    /**////
    /// CustomMarshalAsAttribute implementaion.
    ///
    public sealed class CustomMarshalAsAttribute : Attribute
    {
        public int SizeConst = 0;
        public string  SizeField = null;
    }

            return size;
        }

        virtual and protected methods#region virtual and protected methods

        public static ushort[] ReadUInt16Array(BinaryReader reader, int count)
        {
            ushort[] result = new ushort[count];

        private uint m_InUnknownProtos;
        /**////
        /// 未知协议共收字节数
        ///
        public uint InUnknownProtos
        {
            get { return m_InUnknownProtos; }
            set { m_InUnknownProtos = value; }
        }

namespace Lemony.SystemInfo
{
   
    /**////
    /// CustomMarshaler class implementation.
    ///
    public abstract class CustomMarshaler
    {
        Fields#region Fields
        // The internal buffer
        internal byte[] data;
        private MemoryStream stream;
        private BinaryReader binReader;
        private BinaryWriter binWriter;
       
        #endregion
   
        constructors#region constructors

        static MarshallingMethods()
        {
            // Read Methods
            ReadMethods.Add(typeof(bool), typeof(BinaryReader).GetMethod("ReadBoolean"));
            ReadMethods.Add(typeof(byte), typeof(BinaryReader).GetMethod("ReadByte"));
            ReadMethods.Add(typeof(System.SByte), typeof(BinaryReader).GetMethod("ReadSByte"));
            ReadMethods.Add(typeof(System.Single), typeof(BinaryReader).GetMethod("ReadSingle"));
            ReadMethods.Add(typeof(byte[]), typeof(BinaryReader).GetMethod("ReadBytes"));
            ReadMethods.Add(typeof(char[]), typeof(BinaryReader).GetMethod("ReadChars"));
            ReadMethods.Add(typeof(System.Int16), typeof(BinaryReader).GetMethod("ReadInt16"));
            ReadMethods.Add(typeof(System.Int32), typeof(BinaryReader).GetMethod("ReadInt32"));
            ReadMethods.Add(typeof(System.UInt16), typeof(BinaryReader).GetMethod("ReadUInt16"));
            ReadMethods.Add(typeof(System.UInt32), typeof(BinaryReader).GetMethod("ReadUInt32"));
            ReadMethods.Add(typeof(System.String), typeof(MarshallingMethods).GetMethod("ReadString"));
            ReadMethods.Add(typeof(System.DateTime), typeof(MarshallingMethods).GetMethod("ReadDateTime"));
            ReadMethods.Add(typeof(System.Int16[]), typeof(MarshallingMethods).GetMethod("ReadInt16Array"));
            ReadMethods.Add(typeof(System.Int32[]), typeof(MarshallingMethods).GetMethod("ReadInt32Array"));
            ReadMethods.Add(typeof(System.UInt16[]), typeof(MarshallingMethods).GetMethod("ReadUInt16Array"));
            ReadMethods.Add(typeof(System.UInt32[]), typeof(MarshallingMethods).GetMethod("ReadUInt32Array"));
            ReadMethods.Add(typeof(CustomMarshaler), typeof(CustomMarshaler).GetMethod("ReadFromStream"));
            //Write Methods
            WriteMethods.Add(typeof(bool), typeof(BinaryWriter).GetMethod("Write", new Type[]{typeof(bool)}));
            WriteMethods.Add(typeof(byte), typeof(BinaryWriter).GetMethod("Write", new Type[]{typeof(byte)}));
            WriteMethods.Add(typeof(System.SByte), typeof(BinaryWriter).GetMethod("Write", new Type[]{typeof(System.SByte)}));
            WriteMethods.Add(typeof(System.Single), typeof(BinaryWriter).GetMethod("Write", new Type[]{typeof(System.Single)}));
            //WriteMethods.Add(typeof(byte[]), typeof(BinaryWriter).GetMethod("Write", new Type[]{typeof(byte[])}));
            //WriteMethods.Add(typeof(char[]), typeof(BinaryWriter).GetMethod("Write", new Type[]{typeof(char[])}));
            WriteMethods.Add(typeof(System.Int16), typeof(BinaryWriter).GetMethod("Write", new Type[]{typeof(System.Int16)}));
            WriteMethods.Add(typeof(System.Int32), typeof(BinaryWriter).GetMethod("Write", new Type[]{typeof(System.Int32)}));
            WriteMethods.Add(typeof(System.UInt16), typeof(BinaryWriter).GetMethod("Write", new Type[]{typeof(System.UInt16)}));
            WriteMethods.Add(typeof(System.UInt32), typeof(BinaryWriter).GetMethod("Write", new Type[]{typeof(System.UInt32)}));
            WriteMethods.Add(typeof(System.String), typeof(MarshallingMethods).GetMethod("WriteString"));
            WriteMethods.Add(typeof(CustomMarshaler), typeof(CustomMarshaler).GetMethod("WriteToStream"));

        private string m_PhysAddr;
        /**////
        /// 物理地址
        ///
        public string PhysAddr
        {
            get { return m_PhysAddr; }
            set { m_PhysAddr = value; }
        }

            for(int i=0;i            {
                result[i] = reader.ReadInt16();
            }
            return result;
        }

        helper methods#region helper methods

        private uint m_InErrors;
        /**////
        /// 总错收字节数
        ///
        public uint InErrors
        {
            get { return m_InErrors; }
            set { m_InErrors = value; }
        }

    }
}

        private static bool CompareByteArrays (byte[] data1, byte[] data2)
        {
            // If both are null, they're equal
            if (data1==null && data2==null)
            {
                return true;
            }
            // If either but not both are null, they're not equal
            if (data1==null || data2==null)
            {
                return false;
            }
            if (data1.Length != data2.Length)
            {
                return false;
            }
            for (int i=0; i < data1.Length; i++)
            {
                if (data1[i] != data2[i])
                {
                    return false;
                }
            }
            return true;
        }

先看看怎么定义该 API
[DllImport("IpHlpApi.dll")]
        extern static public uint GetIfTable(byte[] pIfTable, ref uint pdwSize, bool bOrder);
本来想把 pIfTable 定义为 IntPtr,但是这样的结果是,获取的信息是错误的(直到现在都不知是什么原因)。

    #endregion

MIB_IFROW.cs
using System;
using System.Collections.Generic;
using , System.Text;

            foreach (FieldInfo field in fields )
            {
                if (field.FieldType.IsArray)
                {
                    size += GetFieldSize(field);
                }
                else if (field.FieldType == typeof(string))
                {
                    size += GetFieldSize(field)*2;
                }
                else if (field.FieldType.IsPrimitive)
                {
                    size += Marshal.SizeOf(field.FieldType);
                }
            }

        public void Serialize()
        {
            if (data != null)
            {
                stream = new MemoryStream(data);
                binWriter = new BinaryWriter(stream, System.Text.Encoding.Unicode);
                WriteToStream(binWriter);
                binWriter.Close();
            }
        }

        protected int GetFieldSize(FieldInfo field)
        {
            int size = 0;
            CustomMarshalAsAttribute attrib = (CustomMarshalAsAttribute)field.GetCustomAttributes(typeof(CustomMarshalAsAttribute), true)[0];
           
            if (attrib != null)
            {
                if (attrib.SizeField != null)
                {
                    FieldInfo sizeField = this.GetType().GetField(attrib.SizeField);
                    size = (int)sizeField.GetValue(this);
                }
                else
                {
                    size = attrib.SizeConst;   
                }
            }

        private string m_Name;
        /**////
        /// 名称
        ///
        public string Name
        {
            get { return m_Name; }
            set { m_Name = value; }
        }

        public static void WriteArray(BinaryWriter writer, byte[] arr)
        {
            for (int i = 0; i < arr.Length; i++)
            {
                writer.Write(arr[i]);
            }
        }

        public static DateTime ReadDateTime(BinaryReader reader)
        {
            return DateTime.FromFileTime(reader.ReadInt64());
        }

        public byte[] ByteArray
        {
            get
            {
                return data;
            }
        }

        #endregion

        public static void WriteString(BinaryWriter writer, string value, int size)
        {
            if (value!=null)
            {
                byte[] bstring = System.Text.Encoding.Unicode.GetBytes(value.Substring(0, size));
                writer.Write(bstring);
            }
        }

        #endregion

    /**////
    /// 网络状态
    ///
    public enum NetState
    {
        NotOperational = 0,
        Operational = 1,
        Disconnected = 2,
        Connecting = 3,
        Connected = 4,
        Unreachable = 5
    };

namespace Lemony.SystemInfo
{
    /**////
    /// IFTable
    ///
    public class MIB_IFTABLE : CustomMarshaler
    {
        public int dwNumEntries;
        [CustomMarshalAs(SizeField = "dwNumEntries")]
        public MIB_IFROW[] Table;

        private uint m_Index;
        /**////
        /// 有效编号
        ///
        public uint Index
        {
            get { return m_Index; }
            set { m_Index = value; }
        }

        public void Deserialize()
        {
            if (data != null)
            {
                if (binReader != null)
                {
                    binReader.Close();
                    stream.Close();
                }
                // Create a steam from byte array
                stream = new MemoryStream(data);
                binReader = new BinaryReader(stream, System.Text.Encoding.Unicode);
                ReadFromStream(binReader);
                binReader.Close();
            }

            for(int i=0;i            {
                result[i] = reader.ReadUInt16();
            }
            return result;
        }

    /**////
    /// 网络信息类
    ///
    public class NetInfo
    {
        public NetInfo()
        {
        }

        properties#region properties

        public static void WriteArray(BinaryWriter writer, short[] arr)
        {
            for (int i = 0; i < arr.Length; i++)
            {
                writer.Write(arr[i]);
            }
        }
        public static void WriteArray(BinaryWriter writer, ushort[] arr)
        {
            for (int i = 0; i < arr.Length; i++)
            {
                writer.Write(arr[i]);
            }
        }
        public static void WriteArray(BinaryWriter writer, int[] arr)
        {
            for (int i = 0; i < arr.Length; i++)
            {
                writer.Write(arr[i]);
            }
        }
        public static void WriteArray(BinaryWriter writer, uint[] arr)
        {
            for (int i = 0; i < arr.Length; i++)
            {
                writer.Write(arr[i]);
            }
        }
        public static void WriteArray(BinaryWriter writer, long[] arr)
        {
            for (int i = 0; i < arr.Length; i++)
            {
                writer.Write(arr[i]);
            }
        }
        public static void WriteArray(BinaryWriter writer, ulong[] arr)
        {
            for (int i = 0; i < arr.Length; i++)
            {
                writer.Write(arr[i]);
            }
        }
        public static void WriteArray(BinaryWriter writer, float[] arr)
        {
            for (int i = 0; i < arr.Length; i++)
            {
                writer.Write(arr[i]);
            }
        }

本文由10bet发布于Web前端,转载请注明出处:在C#中调用API获取网络信息和流量10bet:

关键词:

最火资讯