精易论坛

标题: 取网卡信息,解决兼容问题 [打印本页]

作者: zxxiaopi    时间: 2024-10-17 10:53
标题: 取网卡信息,解决兼容问题
最近在搞nei网穿透,用到cha询网卡信息并修改,翻了论坛,下载的一些都有些问题,比如兼容性不好,有的在win10是好的,我拿到win7或者windows server2008,2019上去,网卡就枚举有问题了,哎,所以就有了这个dll,c#弄 的,兼容win7~11,server等平台。
[C#] 纯文本查看 复制代码
using System;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using RGiesecke.DllExport;

namespace NetworkInfoDll
{
    public class NetworkInfo
    {
        private static List<NetworkInterface> networkInterfaces;

        [DllExport("GetNetworkAdaptersCount", CallingConvention = CallingConvention.StdCall)]
        public static int GetNetworkAdaptersCount()
        {
            networkInterfaces = new List<NetworkInterface>(NetworkInterface.GetAllNetworkInterfaces());
            return networkInterfaces.Count;
        }

        [DllExport("GetNetworkAdapterInfo", CallingConvention = CallingConvention.StdCall)]
        [return: MarshalAs(UnmanagedType.LPStr)]
        public static string GetNetworkAdapterInfo(int index)
        {
            if (networkInterfaces == null || index < 0 || index >= networkInterfaces.Count)
            {
                return "Error: Invalid index";
            }

            NetworkInterface nic = networkInterfaces[index];
            return GetNetworkAdapterInfoByInterface(nic);
        }

        [DllExport("GetActiveNetworkAdapterInfo", CallingConvention = CallingConvention.StdCall)]
        [return: MarshalAs(UnmanagedType.LPStr)]
        public static string GetActiveNetworkAdapterInfo()
        {
            NetworkInterface activeNic = GetActiveNetworkInterface();
            if (activeNic == null)
            {
                return "Error: No active network adapter found";
            }

            return GetNetworkAdapterInfoByInterface(activeNic);
        }

        [DllExport("SetNetworkAdapterInfo", CallingConvention = CallingConvention.StdCall)]
        [return: MarshalAs(UnmanagedType.LPStr)]
        public static string SetNetworkAdapterInfo(string connectionName, string ipAddress, string subnetMask, string gateway)
        {
            try
            {
                if (!IsAdministrator())
                {
                    return "Error: 需要管理员权限来修改网络设置";
                }

                using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapter"))
                {
                    using (var networkConfigs = networkConfigMng.GetInstances())
                    {
                        foreach (ManagementObject networkAdapter in networkConfigs)
                        {
                            string netConnectionID = networkAdapter["NetConnectionID"] as string;
                            if (netConnectionID == connectionName)
                            {
                                uint index = (uint)networkAdapter["Index"];
                                using (var networkConfigMng2 = new ManagementClass("Win32_NetworkAdapterConfiguration"))
                                {
                                    using (var networkConfigs2 = networkConfigMng2.GetInstances())
                                    {
                                        foreach (ManagementObject networkConfig in networkConfigs2)
                                        {
                                            if ((uint)networkConfig["Index"] == index)
                                            {
                                                ManagementBaseObject newIP = networkConfig.GetMethodParameters("EnableStatic");
                                                newIP["IPAddress"] = new string[] { ipAddress };
                                                newIP["SubnetMask"] = new string[] { subnetMask };

                                                ManagementBaseObject newGateway = networkConfig.GetMethodParameters("SetGateways");
                                                newGateway["DefaultIPGateway"] = new string[] { gateway };

                                                ManagementBaseObject setIP = networkConfig.InvokeMethod("EnableStatic", newIP, null);
                                                ManagementBaseObject setGateway = networkConfig.InvokeMethod("SetGateways", newGateway, null);

                                                if ((uint)setIP["ReturnValue"] == 0 && (uint)setGateway["ReturnValue"] == 0)
                                                {
                                                    return "Success: 网络设置已更新";
                                                }
                                                else
                                                {
                                                    return $"Error: 设置IP返回值 {setIP["ReturnValue"]}, 设置网关返回值 {setGateway["ReturnValue"]}";
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                return $"Error: 未找到名为 '{connectionName}' 的网络连接";
            }
            catch (Exception ex)
            {
                return $"Error: {ex.Message}";
            }
        }

        private static NetworkInterface GetActiveNetworkInterface()
        {
            return NetworkInterface.GetAllNetworkInterfaces()
                .OrderByDescending(nic => nic.Speed)
                .FirstOrDefault(nic =>
                    nic.OperationalStatus == OperationalStatus.Up &&
                    nic.NetworkInterfaceType != NetworkInterfaceType.Loopback &&
                    nic.GetIPProperties().UnicastAddresses.Any(addr => addr.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork));
        }

        private static string GetNetworkAdapterInfoByInterface(NetworkInterface nic)
        {
            IPInterfaceProperties properties = nic.GetIPProperties();

            string connectionName = nic.Name;
            string adapterName = nic.Description;
            string status = GetChineseStatus(nic.OperationalStatus);
            string ipAddress = "";
            string subnetMask = "";
            string gateway = "";

            foreach (UnicastIPAddressInformation ip in properties.UnicastAddresses)
            {
                if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    ipAddress = ip.Address.ToString();
                    subnetMask = ip.IPv4Mask.ToString();
                    break;
                }
            }

            if (properties.GatewayAddresses.Count > 0)
            {
                gateway = properties.GatewayAddresses[0].Address.ToString();
            }

            return $"{connectionName}|{adapterName}|{status}|{ipAddress}|{subnetMask}|{gateway}";
        }

        private static string GetChineseStatus(OperationalStatus status)
        {
            switch (status)
            {
                case OperationalStatus.Up:
                    return "已连接";
                case OperationalStatus.Down:
                    return "已断开";
                case OperationalStatus.Testing:
                    return "正在测试";
                case OperationalStatus.Unknown:
                    return "未知";
                case OperationalStatus.Dormant:
                    return "休眠";
                case OperationalStatus.NotPresent:
                    return "不存在";
                case OperationalStatus.LowerLayerDown:
                    return "底层已断开";
                default:
                    return status.ToString();
            }
        }

        private static bool IsAdministrator()
        {
            System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
            System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
            return principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
        }
    }
}

  
DLL命令名返回值类型公开备 注
获取网卡数量整数型 获取网卡数量:返回值 >= 0: 表示找到的网卡数量,返回值 < 0: 表示出现错误
DLL库文件名:
NetworkInfoDll.dll
在DLL库中对应命令名:
GetNetworkAdaptersCount
参数名类 型传址数组备 注
DLL命令名返回值类型公开备 注
获取网卡信息文本型 获取网卡信息:网卡索引 (从0开始),每一组网卡信息字符串格式:"连接名称|网卡名称|连接状态|IP地址|子网掩码|网关",分隔符是|
DLL库文件名:
NetworkInfoDll.dll
在DLL库中对应命令名:
GetNetworkAdapterInfo
参数名类 型传址数组备 注
网卡索引整数型网卡索引 (从0开始)
DLL命令名返回值类型公开备 注
获取当前联网网卡信息文本型 
DLL库文件名:
NetworkInfoDll.dll
在DLL库中对应命令名:
GetActiveNetworkAdapterInfo
参数名类 型传址数组备 注
DLL命令名返回值类型公开备 注
设置网卡文本型 修改网络设置需要管理员权限,注意修改IP等信息是根据“连接名称“来的
DLL库文件名:
NetworkInfoDll.dll
在DLL库中对应命令名:
SetNetworkAdapterInfo
参数名类 型传址数组备 注
连接名称文本型
新IP文本型
新掩码文本型
新网关文本型

  
窗口程序集名保 留  保 留备 注
窗口程序集_启动窗口   
子程序名返回值类型公开备 注
__启动窗口_创建完毕  
变量名类 型静态数组备 注
a整数型 
i整数型 
a = 获取网卡数量 ()
' 编辑框1.内容 = 到文本 (获取网卡信息 (4))
计次循环首 (a, i)
调试输出 (获取网卡信息 (i - 1))
i = i + 1
计次循环尾 ()
调试输出 (获取当前联网网卡信息 ())
调试输出 (设置网卡 (“WLAN”, “10.36.0.199”, “255.255.255.0”, “10.36.0.1”))


i支持库列表   支持库注释   
spec特殊功能支持库




NetworkInfoDll.rar

4.21 KB, 下载次数: 43, 下载积分: 精币 -2 枚


作者: jysoft2022    时间: 2024-10-17 11:07
谢谢分享
作者: 玩世不恭KISS    时间: 2024-10-17 11:15
谢谢分享
作者: 网络注册网员    时间: 2024-10-17 14:39
谢谢分享
作者: mood1000    时间: 2024-10-17 14:46
感谢分享收藏学习了

作者: 胖子葛格    时间: 2024-10-17 14:48
感谢大神分享~!
作者: pipicool    时间: 2024-10-17 15:05
学习一下
作者: zzh233    时间: 2024-10-17 15:42
能不能拿来做绑定机器用
作者: 深圳梦    时间: 2024-10-17 18:33
支持开源~!感谢分享
作者: 亿万    时间: 2024-10-17 20:33
支持开源~!感谢分享
作者: 艾玛克138    时间: 2024-10-17 20:57
又学到技术了,谢谢老大
作者: 396384183    时间: 2024-10-17 22:37

感谢分享
作者: 尐觅风    时间: 2024-10-18 03:48
瞅瞅!!!!!!!!!!
作者: 查过    时间: 2024-10-18 07:48
感谢分享,很给力!~
作者: year1970    时间: 2024-10-18 08:03
感谢分享
作者: 一指温柔    时间: 2024-10-18 09:40
谢谢分享!~~~~
作者: 小虎来了    时间: 2024-10-18 09:55
感谢大神分享~!
作者: 我的yyy123    时间: 2024-10-18 10:50
学习学习
作者: 嫂子    时间: 2024-10-18 11:01
ManagementClass  是WMI  有些系统(修改版精简版)会缺失的
作者: bianyuan456    时间: 2024-10-18 13:03
已经顶贴,感谢您对论坛的支持!
作者: yangdoudou    时间: 2024-10-19 15:01
谢谢分享
作者: happyweeks365    时间: 2024-10-19 15:36
66666666666666666666666666
作者: please    时间: 2024-10-20 09:37
感谢分享,支持开源!!!
作者: please    时间: 2024-10-21 09:38
感谢分享,支持开源!!!
作者: 胖子葛格    时间: 2024-10-22 10:24
感谢大神分享~!
作者: 光影魔术    时间: 2024-10-24 10:38
感谢分享源码
作者: Eroslp    时间: 2024-10-24 22:14
感谢分享!!!u49PvU1x1U
作者: Eroslp    时间: 2024-10-25 07:27
感谢分享!!!QeCeMcMmtr
作者: 陈兴华    时间: 2024-10-26 22:35
网卡如果禁用就找不到了
作者: 胖子葛格    时间: 2024-10-28 10:19
感谢大神分享~!
作者: 飞翔蓝天    时间: 2024-11-12 18:15
很感谢你的分享,
作者: qq43142691    时间: 2024-12-3 21:00
正在进行名称连接... 错误(10003): 指定Dll命令名称“获取网卡数量”未找到。
作者: 熊不熊    时间: 2024-12-4 08:18
感谢分享,很给力!~
作者: 股老传奇    时间: 2025-3-2 12:16
666666666666666666




欢迎光临 精易论坛 (https://125.confly.eu.org/) Powered by Discuz! X3.4