欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-01-11 07:51:07
界面效果图如下: 报表界面 说下关键代码  需要开启 windows management instrumentation服务(默认已经开启),在程...

界面效果图如下:

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

报表界面

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);
      }

    }

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