C # network adapter simple Operation _c# Tutorial

Source: Internet
Author: User

The related setting of network has more application in the project development, sometimes it is necessary to set up the network information in the project.

Now provides several related helper method classes.

(1). IP Address

<summary>
  ///IP address
  ///</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). Gateway Address

  <summary>
  ///gateway address
  ///</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 server address

  <summary>
  ///DHCP server address
  ///</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 address

  <summary>
  ///mac address
  ///</summary> public
  string macaddres
  {
   get
   {
    string macAddress;
    if (MacAddress = = null)
     MacAddress = string. Empty;
    else if (macaddress.tostring (). Length = =
    {
     macAddress = macaddress.tostring (). Insert (4, "-"). Insert (9, "-");
    }
    else
    {
     macAddress = macaddress.tostring ();
    }
    return macAddress;
   }
   set {if (value = = null) throw new ArgumentNullException (nameof (value));}
  

(5). Primary DNS Address

  <summary>
  ///Primary DNS address
  ///</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). Alternate DNS Address

  <summary>
  ///Alternate DNS address
  ///</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). Subnet mask

  <summary>
  ///Subnet mask
  ///</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). property

 <summary>///DNS Collection///</summary> public ipaddresscollection dnsaddresses {get; set;} <summary>///Gateway Address collection///</summary> public gatewayipaddressinformationcollection getwaryes {get; SE T ///<summary>///IP Address collection///</summary> public unicastipaddressinformationcollection ipaddresses { Get Set ///<summary>///DHCP address collection///</summary> public ipaddresscollection dhcpserveraddresses {get; set ;

  ///<summary>///Nic mac address///</summary> public physicaladdress MacAddress {get; set;}

  <summary>///Enable DHCP service///</summary> public bool isdhcpenabled {get; set;}
  <summary>///Description Information///</summary> public string Description {get; set;} <summary>///Network interface type///</summary>///<returns></returns> public string Networkinter

  Facetype {get; set;} <summary>///Speed///;/summary> public string Speed {get; set;}

 

(9). Whether it is an IP address

  <summary>
  ///is IP address
  ///</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). Enable DHCP service

  <summary>
  ///Enable DHCP service
  ///</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);
   }
   Query current Adapter interface Information
   var networkadapter = new Networkadapterutil (). Getneworkadapterbynetworkinterfaceid (Networkinterfaceid); 
   return networkadapter!= null && networkadapter.isdhcpenabled;
  }

(11). Set IP address, subnet mask, gateway, DNS

 <summary>
  ///Set IP address, subnet mask, gateway, DNS,
  ///</summary> public
  bool Setipaddresssubmaskdnsgetway (String ipaddress, String submask, String Getway, String Dnsmain, String dnsbackup)
  { C5/>string[] Dnsarray;
   if (string. IsNullOrEmpty (dnsbackup))
   {
    Dnsarray = new[] {dnsmain};
   }
   else
   {
    Dnsarray = new[] {dnsmain, dnsbackup};
   }
   Return Setipaddress (new[] {ipaddress}, new[] {submask}, new[] {getway}, Dnsarray);

  <summary>
  ///Set IP address and subnet mask
  ///</summary> public
  bool Setipaddressandsubmask (string IPAddress, string submask)
  {return
   setipaddress (new[] {ipaddress}, new[] {submask}, NULL, NULL);


  ///<summary>
  ///set IP gateway
  ///</summary> public
  bool Setgetwayaddress (string getway)
  {return
   setipaddress (null, NULL, new[] {getway}, NULL);

  }

(12). Set up master, backup DNS address

  <summary>
  ///Settings Master, backup DNS address
  ///</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). Get IPV4 Address

  <summary>
  ///Get IPV4 address
  ///</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). Check Set IP address, if return null, means check pass, in order to facilitate return on string

  <summary>///Check Set IP address, if returned empty, means check pass, in order to facilitate return on string, no use enumerated///</summary>///<param name= "Ipaddres S "></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 "Wrong IP address format"; } if (!string. IsNullOrEmpty (Submask)) {if (!
   Isipaddress (Submask)) return "Subnet mask format is incorrect"; } if (!string. IsNullOrEmpty (Getway)) {if (!
   Isipaddress (Getway)) return "gateway address format is not correct"; } if (!string. IsNullOrEmpty (Dnsmain)) {if (!
   Isipaddress (Dnsmain)) return "Primary DNS address format is not correct"; } if (string.
   IsNullOrEmpty (dnsbackup)) return ""; Return! Isipaddress (dnsbackup)?
"Alternate DNS address format is not correct": "";  }

 

(15). Set IP address

  <summary>///Set IP address///</summary>///<param name= "IP" ></param>///<param Nam E= "Submask" ></param>///<param name= "Getway" ></param>///<param name= "DNS" ></param&
  Gt private bool Setipaddress (IEnumerable IP, IEnumerable submask, IEnumerable getway, IEnumerable DNS) {var WMI = new M
   Anagementclass ("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"); Gets the return value of the Operation setting IP, which confirms that the IP is set to succeed based on the return value. 0 or 1 indicates success} 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;

 }

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.