C # set local networks such as DNS, gateway, subnet mask, IP address, etc.

Source: Internet
Author: User

Nowadays, the Internet is playing an increasingly important role in our daily lives and work. It can be said that without the Internet, we will not be able to work and live normally. As a programmer, most of the programs we write will also be related to the network. To use the network, you must first set the network configuration of the machine. The manual setting method is obviously not desirable, so we need to let the program complete it for us. The following is a very common Demo of C # setting various network parameters of the system.

This Demo is based on the "Win32_NetworkAdapterConfiguration" management class. The configuration information of IP, DNS, and gateway is basically included.

Using WMI in C # is relatively simple:
Copy codeThe Code is as follows:
Using System;
Using System. Collections. Generic;
Using System. Text;
Using System;
Using System. Collections;
Using System. Text;
Using System. Management;
Using System. Text. RegularExpressions;


Namespace Demo
{
/// <Summary>
/// Network settings class, set various network parameters (DNS, gateway, subnet mask, IP)
/// </Summary>
Public class NetworkSetting
{
Public NetworkSetting ()
{
// Constructor Logic
}

/// <Summary>
/// Set DNS
/// </Summary>
/// <Param name = "dns"> </param>
Public static void SetDNS (string [] dns)
{
SetIPAddress (null, dns );
}
/// <Summary>
/// Configure the Gateway
/// </Summary>
/// <Param name = "getway"> </param>
Public static void SetGetWay (string getway)
{
SetIPAddress (null, null, new string [] {getway}, null );
}
/// <Summary>
/// Configure the Gateway
/// </Summary>
/// <Param name = "getway"> </param>
Public static void SetGetWay (string [] getway)
{
SetIPAddress (null, null, getway, null );
}
/// <Summary>
/// Set the IP address and mask
/// </Summary>
/// <Param name = "ip"> </param>
/// <Param name = "submask"> </param>
Public static void SetIPAddress (string ip, string submask)
{
SetIPAddress (new string [] {ip}, new string [] {submask}, null, null );
}
/// <Summary>
/// Set the IP address, mask, and gateway
/// </Summary>
/// <Param name = "ip"> </param>
/// <Param name = "submask"> </param>
/// <Param name = "getway"> </param>
Public static void SetIPAddress (string ip, string submask, string getway)
{
SetIPAddress (new string [] {ip}, new string [] {submask}, new string [] {getway}, null );
}
/// <Summary>
/// Set the IP address, mask, gateway, and DNS
/// </Summary>
/// <Param name = "ip"> </param>
/// <Param name = "submask"> </param>
/// <Param name = "getway"> </param>
/// <Param name = "dns"> </param>
Public static void 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;
Foreach (ManagementObject mo in moc)
{
// Skip this step if no network device with IP settings Enabled
If (! (Bool) mo ["IPEnabled"])
Continue;

// Set the IP address and mask
If (ip! = Null & submask! = Null)
{
InPar = mo. GetMethodParameters ("EnableStatic ");
InPar ["IPAddress"] = ip;
InPar ["SubnetMask"] = submask;
OutPar = mo. InvokeMethod ("EnableStatic", inPar, null );
}

// Set the gateway address
If (getway! = Null)
{
InPar = mo. GetMethodParameters ("SetGateways ");
InPar ["DefaultIPGateway"] = getway;
OutPar = mo. InvokeMethod ("SetGateways", inPar, null );
}

// Set the DNS address
If (dns! = Null)
{
InPar = mo. GetMethodParameters ("SetDNSServerSearchOrder ");
InPar ["DNSServerSearchOrder"] = dns;
OutPar = mo. InvokeMethod ("SetDNSServerSearchOrder", inPar, null );
}
}
}

/// <Summary>
/// Enable the DHCP server
/// </Summary>
Public static void EnableDHCP ()
{
ManagementClass wmi = new ManagementClass ("Win32_NetworkAdapterConfiguration ");
ManagementObjectCollection moc = wmi. GetInstances ();
Foreach (ManagementObject mo in moc)
{
// Skip this step if no network device with IP settings Enabled
If (! (Bool) mo ["IPEnabled"])
Continue;
// Reset DNS to null
Mo. InvokeMethod ("SetDNSServerSearchOrder", null );
// Enable DHCP
Mo. InvokeMethod ("EnableDHCP", null );
}
}

/// <Summary>
/// Determine whether the IP address format is correct
/// </Summary>
/// <Param name = "ip"> </param>
/// <Returns> </returns>
Public static bool IsIPAddress (string ip)
{
// Group the complete IP Address "."
String [] arr = ip. Split ('.');


// Determine whether the IP address is composed of four groups
If (arr. Length! = 4)
Return false;


// Regular expression, 1 ~ 3-digit integer
String pattern = @ "\ d {1, 3 }";
For (int I = 0; I <arr. Length; I ++)
{
String d = arr [I];


// Determine whether the start of the IP address is 0
If (I = 0 & d = "0 ")
Return false;


// Determine whether the IP address is from 1 ~ Three-digit Structure
If (! Regex. IsMatch (d, pattern ))
Return false;

If (d! = "0 ")
{
// Determine whether all IP addresses in each group are 0
D = d. TrimStart ('0 ');
If (d = "")
Return false;

// Determine whether the number of IP addresses in each group is greater than 255
If (int. Parse (d)> 255)
Return false;
}
} Return true;
}
}
}

Well, after writing the above class, you can simply wait for where you need it and then create a NEW one. It's easy. If the setting fails, it may be because of insufficient permissions. For details, refer to C # running the program as an administrator by default.

Related Article

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.