C#实现获取设置IP地址小工具

界面效果图如下:

报表界面

说下关键代码

需要开启 Windows Management Instrumentation服务(默认已经开启),在程序中需要增加 Management引用。

主要有NetworkAdapter(保存适配器的IP地址,网关,子网掩码,设置IP方面等 ),NetworkAdapterUtil(主要是NetworkAdapter类的集合 )两个类。

在windows8 需要在app.manifest文件中

修改配置  <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />,不然就算有管理员权限也修改不了IP地址。

1 设置IP地址的代码。(设置IP地址,修改IP地址需要管理员权限)

  /// <summary>
  /// 网络适配器类
  /// </summary>
  public class NetworkAdapter
  { 

/// <summary>
    /// 设置IP地址
    /// </summary>
    /// <param name="ip"></param>
    /// <param name="submask"></param>
    /// <param name="getway"></param>
    /// <param name="dns"></param>
    private bool SetIPAddress(string[] ip, string[] submask, string[] getway, string[] dns)
    {
      ManagementClass wmi = new ManagementClass("Win32_NetworkAdapterConfiguration");
      ManagementObjectCollection moc = wmi.GetInstances();
      ManagementBaseObject inPar = null;
      ManagementBaseObject outPar = null;
      string str = "";
      foreach (ManagementObject mo in moc)
      {

        if (!(bool)mo["IPEnabled"])
          continue;

        if (this.NetworkInterfaceID == mo["SettingID"].ToString())
        {
          if (ip != null && submask != null)
          {
            string caption = mo["Caption"].ToString(); //描述
            inPar = mo.GetMethodParameters("EnableStatic");
            inPar["IPAddress"] = ip;
            inPar["SubnetMask"] = submask;
            outPar = mo.InvokeMethod("EnableStatic", inPar, null);
            str = outPar["returnvalue"].ToString();
            return (str=="0"||str=="1")?true:false;
             //获取操作设置IP的返回值, 可根据返回值去确认IP是否设置成功。 0或1表示成功
            // 返回值说明网址: https://msdn.microsoft.com/en-us/library/aa393301(v=vs.85).aspx
          }
          if(getway!=null)
          {
            inPar = mo.GetMethodParameters("SetGateways");
            inPar["DefaultIPGateway"] = getway;
            outPar = mo.InvokeMethod("SetGateways", inPar, null);
            str = outPar["returnvalue"].ToString();
            return (str == "0" || str == "1") ? true : false;
          }
          if (dns != null)
          {
            inPar = mo.GetMethodParameters("SetDNSServerSearchOrder");
            inPar["DNSServerSearchOrder"] = dns;
            outPar = mo.InvokeMethod("SetDNSServerSearchOrder", inPar, null);
            str = outPar["returnvalue"].ToString();
            return (str == "0" || str == "1") ? true : false;
          }

        }
      }
      return false;
    }
}

2 设置IP为自动获取

   /// <summary>
    /// 启用DHCP服务
    /// </summary>
    public void EnableDHCP()
    {

      ManagementClass wmi = new ManagementClass("Win32_NetworkAdapterConfiguration");
      ManagementObjectCollection moc = wmi.GetInstances();
      foreach (ManagementObject mo in moc)
      {
        if (!(bool)mo["IPEnabled"])
          continue;

        if (mo["SettingID"].ToString() == this.NetworkInterfaceID) //网卡接口标识是否相等, 相当只设置指定适配器IP地址
        {
          mo.InvokeMethod("SetDNSServerSearchOrder", null);
          mo.InvokeMethod("EnableDHCP", null);

        }
      }
    }

  3. 获取所有适配器

public class NetworkAdapterUtil
{

 /// <summary>
    /// 获取所有适配器类型,适配器被禁用则不能获取到
    /// </summary>
    /// <returns></returns>
    public List<NetworkAdapter> GetAllNetworkAdapters() //如果适配器被禁用则不能获取到
    {
      IEnumerable<NetworkInterface> adapters = NetworkInterface.GetAllNetworkInterfaces(); //得到所有适配器
      return GetNetworkAdapters(adapters);

    }

 /// <summary>
   /// 根据条件获取IP地址集合,
   /// </summary>
    /// <param name="adapters">网络接口地址集合</param>
   /// <param name="adapterTypes">网络连接状态,如,UP,DOWN等</param>
   /// <returns></returns>
    private List<NetworkAdapter> GetNetworkAdapters(IEnumerable<NetworkInterface> adapters, params NetworkInterfaceType[] networkInterfaceTypes)
    {
      adapterList = new List<NetworkAdapter>();

      foreach (NetworkInterface adapter in adapters)
      {
        if (networkInterfaceTypes.Length <=0) //如果没传可选参数,就查询所有
        {
          if (adapter != null)
          {
            NetworkAdapter adp = SetNetworkAdapterValue(adapter);
            adapterList.Add(adp);
          }
          else
          {
            return null;
          }
        }
        else //过滤查询数据
        {
          foreach (NetworkInterfaceType networkInterfaceType in networkInterfaceTypes)
          {
            if (adapter.NetworkInterfaceType.ToString().Equals(networkInterfaceType.ToString()))
            {
              adapterList.Add(SetNetworkAdapterValue(adapter));
              break; //退出当前循环
            }
          }
        }
      }
      return adapterList;
    }

 /// <summary>
   /// 设置网络适配器信息
   /// </summary>
   /// <param name="adapter"></param>
   /// <returns></returns>
   private NetworkAdapter SetNetworkAdapterValue(NetworkInterface adapter)
   {
     NetworkAdapter networkAdapter = new NetworkAdapter();
     IPInterfaceProperties ips = adapter.GetIPProperties();
     networkAdapter.Description = adapter.Name;
     networkAdapter.NetworkInterfaceType = adapter.NetworkInterfaceType.ToString();
     networkAdapter.Speed = adapter.Speed / 1000 / 1000 + "MB"; //速度
     networkAdapter.MacAddress = adapter.GetPhysicalAddress(); //物理地址集合
     networkAdapter.NetworkInterfaceID = adapter.Id;//网络适配器标识符

     networkAdapter.Getwaryes = ips.GatewayAddresses; //网关地址集合
     networkAdapter.IPAddresses = ips.UnicastAddresses; //IP地址集合
     networkAdapter.DhcpServerAddresses = ips.DhcpServerAddresses;//DHCP地址集合
     networkAdapter.IsDhcpEnabled =ips.GetIPv4Properties()==null?false: ips.GetIPv4Properties().IsDhcpEnabled; //是否启用DHCP服务

     IPInterfaceProperties adapterProperties = adapter.GetIPProperties();//获取IPInterfaceProperties实例
     networkAdapter.DnsAddresses = adapterProperties.DnsAddresses; //获取并显示DNS服务器IP地址信息 集合
     return networkAdapter;
   }
  }

}

4  启用, 禁用适配器代码

    /// <summary>
    /// 启用所有适配器
    /// </summary>
    /// <returns></returns>
    public void EnableAllAdapters()
    {
     // ManagementClass wmi = new ManagementClass("Win32_NetworkAdapter");
     // ManagementObjectCollection moc = wmi.GetInstances();
      System.Management.ManagementObjectSearcher moc = new System.Management.ManagementObjectSearcher("Select * from Win32_NetworkAdapter where NetEnabled!=null ");
      foreach (System.Management.ManagementObject mo in moc.Get())
      {
        //if (!(bool)mo["NetEnabled"])
        //  continue;
        string capation = mo["Caption"].ToString();
        string descrption =mo["Description"].ToString();
        mo.InvokeMethod("Enable",null);
      }

    }

    /// <summary>
    /// 禁用所有适配器
    /// </summary>
    public void DisableAllAdapters()
    {
      // ManagementClass wmi = new ManagementClass("Win32_NetworkAdapter");
      // ManagementObjectCollection moc = wmi.GetInstances();
      System.Management.ManagementObjectSearcher moc = new System.Management.ManagementObjectSearcher("Select * from Win32_NetworkAdapter where NetEnabled!=null ");
      foreach (System.Management.ManagementObject mo in moc.Get())
      {
        //if ((bool)mo["NetEnabled"])
        //  continue;
        string capation = mo["Caption"].ToString();
        string descrption = mo["Description"].ToString();
        mo.InvokeMethod("Disable", null);
      }

    }

以上所述就是本文的全部内容了,希望大家能够喜欢。

(0)

相关推荐

  • C#通过域名获得IP地址的方法

    本文实例讲述了C#通过域名获得IP地址的方法.分享给大家供大家参考.具体实现方法如下: using System.Net; string web = txtWeb.Text; IPHostEntry host = Dns.GetHostByName(web); IPAddress ip = host.AddressList[0]; txtIp.Text = ip.ToString(); 希望本文所述对大家的C#程序设计有所帮助.

  • c#获取本机的IP地址的代码

    复制代码 代码如下: public static IPAddress GetHostIP(){            IPHostEntry ipe = Dns.GetHostEntry(Dns.GetHostName());            IPAddress ip = ipe.AddressList[0]; return ip;} private String GetIPAddress(){            String str;            String Result

  • c#判断正确的ip地址格式示例

    判断ip地址是否正确,直接用.Net现成的类,方法如下 复制代码 代码如下: string ipStr="192.168.222.333";IPAddress ip;if(IPAddress.TryParse(ipStr,out ip)){   Console.WriterLine("合法IP");}else{   Console.WriterLine("非法IP");}

  • C#获取真实IP地址实现方法

    本文实例讲述了C#获取真实IP地址实现方法,分享给大家供大家参考.具体实现方法如下: 通常来说,大家获取用户IP地址常用的方法是: 复制代码 代码如下: string IpAddress = ""; if((HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]!=null && HttpContext.Current.Request.ServerVariables[&q

  • c#获取本机在局域网ip地址的二种方法

    复制代码 代码如下: /// <summary>/// 获取本机在局域网的IP地址/// </summary>/// <returns></returns>private string GetLocalIPAddress(){    System.Net.IPAddress[] addressList = Dns.GetHostEntry(Dns.GetHostName()).AddressList;    string strNativeIP = &quo

  • C#获取本机IP地址和Mac地址的方法

    本文实例讲述了C#获取本机IP地址和Mac地址的方法.分享给大家供大家参考.具体分析如下: 查找了几个方法,经过调试修改,下面这个方法能很好的获取到本地的IP和MAC地址.可以用于这方面的功能实现.主要是要添加System.Management的引用. using System; using System.Management; using System.Net; public class Program { static void Main(string[] args) { try { str

  • C#编程获取IP地址的方法示例

    本文实例讲述了C#编程获取IP地址的方法.分享给大家供大家参考,具体如下: 1.获取客户端IP /// <summary> /// 获取客户端Ip /// </summary> /// <returns></returns> public String GetClientIp() { String clientIP = ""; if (System.Web.HttpContext.Current != null) { clientIP =

  • winform C#获得Mac地址,IP地址,子网掩码,默认网关的实例

    1.  添加程序集 2.  引入命名空间 using System.Management; 3.  方法 ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection nics = mc.GetInstances(); foreach (ManagementObject nic in nics) { if (Convert.ToBoole

  • C#正则表达式分解和转换IP地址实例(C#正则表达式大全 c#正则表达式语法)

    只能输入数字:"^[0-9]*$". 只能输入n位的数字:"^\d{n}$". 只能输入至少n位的数字:"^\d{n,}$". 只能输入m~n位的数字:."^\d{m,n}$" 只能输入零和非零开头的数字:"^(0|[1-9][0-9]*)$". 只能输入有两位小数的正实数:"^[0-9]+(.[0-9]{2})?$". 只能输入有1~3位小数的正实数:"^[0-9]+(.[0

  • C#获取真实IP地址(IP转为长整形、判断是否内网IP的方法)

    今天查看登录日志,发现http_x_forwarded_for获取到的ip地址有些是内网ip地址,有些则是公网和内网ip地址一起获取到,用逗号分隔开,日志截图如下: 之前获取ip地址的C#代码如下: 复制代码 代码如下: /// <summary>     /// C#获取客户端真实IP地址     /// </summary>     /// <returns></returns>     public static string GetIP()    

  • C#实现生成mac地址与IP地址注册码的两种方法

    本文实例讲述了C#实现生成mac地址与IP地址注册码的两种方法,分享给大家供大家参考之用.具体方法如下: 方法一: using System; using System.Management; using System.Security.Cryptography; using System.IO; using System.Collections.Generic; using System.Text; namespace xingming_reg { class Program { static

随机推荐