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

c# 如何对网络信息进行相关设置(ip,dns,网关等)

程序员文章站 2022-03-17 18:04:06
网络的相关设置在项目开发中有较多的应用,有时候需要在项目中对网络信息进行相关设置。 现在提供提供几种相关的辅助方法类。(1).ip地址 /// /// ip地址...

     网络的相关设置在项目开发中有较多的应用,有时候需要在项目中对网络信息进行相关设置。

     现在提供提供几种相关的辅助方法类。

(1).ip地址

  /// <summary>
  /// ip地址
  /// </summary>
  public string ipaddress
  {
   get
   {
    string ipaddress;
    var address = getaddress();
    if (address == null)
    {
     ipaddress = string.empty;
    }
    else
    {
     ipaddress = address.address.tostring();
    }
    return ipaddress;
   }
   set { if (value == null) throw new argumentnullexception(nameof(value)); }
  }

(2).网关地址

  /// <summary>
  /// 网关地址
  /// </summary>
  public string getway
  {
   get
   {    
    string getway;
    if (getwaryes != null && getwaryes.count > 0)
    {

     getway = getwaryes[0].address.tostring() == "0.0.0.0" ? "" : getwaryes[0].address.tostring(); 
    }
    else
    {
     getway =string.empty;
    }
    return getway;
   }
   set { if (value == null) throw new argumentnullexception(nameof(value)); }
  }

(3). dhcp服务器地址

  /// <summary>
  /// dhcp服务器地址
  /// </summary>
  public string dhcpserver
  {
   get
   {
    string dhcpserver;
    if (dhcpserveraddresses != null && dhcpserveraddresses.count > 0)
    {
     dhcpserver = dhcpserveraddresses[0].tostring();
    }
    else
    {
     dhcpserver = string.empty;
    }
    return dhcpserver;
   }
   set { if (value == null) throw new argumentnullexception(nameof(value)); }
  }

(4).mac地址

  /// <summary>
  /// mac地址
  /// </summary>
  public string macaddres
  {
   get
   {
    string macaddress;
    if (macaddress == null)
     macaddress = string.empty;
    else if (macaddress.tostring().length == 12)
    {
     macaddress = macaddress.tostring().insert(4, "-").insert(9, "-");
    }
    else
    {
     macaddress = macaddress.tostring();
    }
    return macaddress;
   }
   set { if (value == null) throw new argumentnullexception(nameof(value)); }
  }

(5). 主dns地址

  /// <summary>
  /// 主dns地址
  /// </summary>
  public string dnsmain
  {
   get
   {
    var dnsmain =string.empty;

    if (dnsaddresses.count > 0)
    {
     if (isipaddress(dnsaddresses[0].tostring()))
     {
      dnsmain = dnsaddresses[0].tostring();
     }
    }
    else
    {
     dnsmain =string.empty;
    }
    return dnsmain;
   }
   set { if (value == null) throw new argumentnullexception(nameof(value)); }
  }

(6).备用dns地址

  /// <summary>
  /// 备用dns地址
  /// </summary>
  public string dnsbackup
  {
   get
   {
    var dnsbackup = string.empty;
    if (dnsaddresses.count > 1)
    {
     if (isipaddress(dnsaddresses[1].tostring()))
     {
      dnsbackup = dnsaddresses[1].tostring();
     }

    }
    else
    {
     dnsbackup = string.empty;
    }
    return dnsbackup;
   }
   set { if (value == null) throw new argumentnullexception(nameof(value)); }
  }

(7).子网掩码

  /// <summary>
  /// 子网掩码
  /// </summary>
  public string mask
  {
   get
   {
    string mask;
    var address = getaddress();
    if (address == null)
    {
     mask = "";
    }
    else
    {
     if (address.ipv4mask != null) 
     {
      mask = address.ipv4mask.tostring();
     }
     else
     {
      mask = "255.255.255.0";
     }
     
    }
    return mask;
   }
   set { if (value == null) throw new argumentnullexception(nameof(value)); }
  }

(8).属性

  /// <summary>
  /// dns集合
  /// </summary>
  public ipaddresscollection dnsaddresses { get; set; }
  /// <summary>
  /// 网关地址集合
  /// </summary>
  public gatewayipaddressinformationcollection getwaryes { get; set; }

  /// <summary>
  /// ip地址集合
  /// </summary>
  public unicastipaddressinformationcollection ipaddresses { get; set; }

  /// <summary>
  /// dhcp地址集合
  /// </summary>
  public ipaddresscollection dhcpserveraddresses { get; set; }

  /// <summary>
  /// 网卡mac地址
  /// </summary>
  public physicaladdress macaddress { get; set; }

  /// <summary>
  /// 是否启用dhcp服务
  /// </summary>
  public bool isdhcpenabled { get; set; }

  /// <summary>
  /// 描述信息
  /// </summary>
  public string description { get; set; }
  /// <summary>
  /// 网络接口类型
  /// </summary>
  /// <returns></returns>
  public string networkinterfacetype { get; set; }

  /// <summary>
  /// 速度
  /// </summary>
  public string speed { get; set; } 

(9).是否是ip地址

  /// <summary>
  /// 是否是ip地址
  /// </summary>
  /// <param name="ipaddress"></param>
  /// <returns></returns>
  public bool isipaddress(string ipaddress)
  {
   const string regexstr = @"^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$";
   var regex = system.text.regularexpressions.regex.match(ipaddress, regexstr);
   return regex.success;
  }

(10).启用dhcp服务

  /// <summary>
  /// 启用dhcp服务
  /// </summary>
  public bool enabledhcp()
  {
   var wmi = new managementclass("win32_networkadapterconfiguration");
   var moc = wmi.getinstances();
   foreach (var o in moc)
   {
    var mo = (managementobject) o;
    if (!(bool)mo["ipenabled"])
     continue;
    if (mo["settingid"].tostring() != networkinterfaceid) continue;
    mo.invokemethod("setdnsserversearchorder", null);
    mo.invokemethod("enabledhcp", null);
   }
   //查询现适配器接口信息
   var networkadapter = new networkadapterutil().getneworkadapterbynetworkinterfaceid(networkinterfaceid); 
   return networkadapter != null && networkadapter.isdhcpenabled;
  }

(11).设置ip地址,子网掩码,网关,dns

  /// <summary>
  /// 设置ip地址,子网掩码,网关,dns,
  /// </summary>
  public bool setipaddresssubmaskdnsgetway(string ipaddress, string submask, string getway, string dnsmain, string dnsbackup)
  {
   string[] dnsarray;
   if (string.isnullorempty(dnsbackup))
   {
    dnsarray = new[] { dnsmain };
   }
   else
   {
    dnsarray = new[] { dnsmain, dnsbackup };
   }
   return setipaddress(new[] { ipaddress }, new[] { submask }, new[] { getway }, dnsarray);

  }

  /// <summary>
  /// 设置ip地址和子网掩码
  /// </summary>
  public bool setipaddressandsubmask(string ipaddress, string submask)
  {
   return setipaddress(new[] { ipaddress }, new[] { submask }, null, null);

  }


  /// <summary>
  /// 设置ip网关
  /// </summary>
  public bool setgetwayaddress(string getway)
  {
   return setipaddress(null, null, new[] { getway }, null);

  }

(12).设置主,备份dns地址

  /// <summary>
  /// 设置主,备份dns地址
  /// </summary>
  public bool setdnsaddress(string dnsmain, string dnsbackup)
  {
   string[] dnsarray;
   if (string.isnullorempty(dnsbackup))
   {
    dnsarray = new[] { dnsmain };
   }
   else
   {
    dnsarray = new[] { dnsmain, dnsbackup };
   }
   return setipaddress(null, null, null, dnsarray);

  }

(13).得到ipv4地址

  /// <summary>
  /// 得到ipv4地址
  /// </summary>
  /// <returns></returns>
  private unicastipaddressinformation getaddress()
  {
   if (ipaddresses == null || ipaddresses.count <= 0) return null;
   switch (ipaddresses.count)
   {
    case 3:
     return ipaddresses[2];
    case 2:
     return ipaddresses[1];
   }
   return ipaddresses[0];
  }

(14).检查设置ip地址,如果返回空,表示检查通过,为了方便返回就字符串了

  /// <summary>
  /// 检查设置ip地址,如果返回空,表示检查通过,为了方便返回就字符串了,没用枚举了
  /// </summary>
  /// <param name="ipaddress"></param>
  /// <param name="submask"></param>
  /// <param name="getway"></param>
  /// <param name="dnsmain"></param>
  /// <param name="dnsbackup"></param>
  /// <returns></returns>
  public string isipaddress(string ipaddress, string submask, string getway, string dnsmain, string dnsbackup)
  {
   if (!string.isnullorempty(ipaddress))
   {
    if (!isipaddress(ipaddress)) return "ip地址格式不对";
   }
   if (!string.isnullorempty(submask))
   {
    if (!isipaddress(submask)) return "子网掩码格式不对";
   }
   if (!string.isnullorempty(getway))
   {
    if (!isipaddress(getway)) return "网关地址格式不对";
   }
   if (!string.isnullorempty(dnsmain))
   {
    if (!isipaddress(dnsmain)) return "主dns地址格式不对";
   }
   if (string.isnullorempty(dnsbackup)) return "";
   return !isipaddress(dnsbackup) ? "备用dns地址格式不对" : "";
  }

(15).设置ip地址

  /// <summary>
  /// 设置ip地址
  /// </summary>
  /// <param name="ip"></param>
  /// <param name="submask"></param>
  /// <param name="getway"></param>
  /// <param name="dns"></param>
  private bool setipaddress(ienumerable ip, ienumerable submask, ienumerable getway, ienumerable dns)
  {
   var wmi = new managementclass("win32_networkadapterconfiguration");
   var moc = wmi.getinstances();
   foreach (var o in moc)
   {
    var mo = (managementobject) o;
    if (!(bool)mo["ipenabled"])
     continue;
    if (networkinterfaceid != mo["settingid"].tostring()) continue;
    managementbaseobject inpar;
    managementbaseobject outpar;
    string str = null;
    if (ip != null && submask != null)
    {
     inpar = mo.getmethodparameters("enablestatic");
     inpar["ipaddress"] = ip;
     inpar["subnetmask"] = submask;
     outpar = mo.invokemethod("enablestatic", inpar, null);
     if (outpar != null) str = outpar["returnvalue"].tostring();
     return (str=="0"||str=="1");
     //获取操作设置ip的返回值, 可根据返回值去确认ip是否设置成功。 0或1表示成功
    }
    if(getway!=null)
    {
     inpar = mo.getmethodparameters("setgateways");
     inpar["defaultipgateway"] = getway;
     outpar = mo.invokemethod("setgateways", inpar, null);
     if (outpar != null) str = outpar["returnvalue"].tostring();
     return (str == "0" || str == "1");
    }
    if (dns == null) continue;
    inpar = mo.getmethodparameters("setdnsserversearchorder");
    inpar["dnsserversearchorder"] = dns;
    outpar = mo.invokemethod("setdnsserversearchorder", inpar, null);
    if (outpar != null) str = outpar["returnvalue"].tostring();
    return (str == "0" || str == "1");
   }
   return false;
  } 

以上就是c# 网络适配器的相关操作的详细内容,更多关于c# 网络适配器操作的资料请关注其它相关文章!