using System;
using System.Collections.Generic;
using System.Text;
using System.Management;
using DynamicMAC;
namespace InsteadIP
{
public class SetAndRead
{
public SetAndRead()
{
ShowNetworkAdapterInfo();
//SetNetworkAdapter();
//ShowNetworkAdapterInfo();
}
///
/// set
///
///
///
///
///
///
public static void SetNetworkAdapter(string[] str)
{
string ip = str[0];
string subnetmask = str[1];
string DefaultIPGateway = str[2];
string DNS = str[3];
string MAC = str[4];
ManagementBaseObject inPar = null;
ManagementBaseObject outPar = null;
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if (!(bool)mo["IPEnabled"])
continue;
//设置ip地址和子网掩码
inPar = mo.GetMethodParameters("EnableStatic");
inPar["IPAddress"] = new string[] { ip };
inPar["SubnetMask"] = new string[] { subnetmask };
outPar = mo.InvokeMethod("EnableStatic", inPar, null);
//设置网关地址
inPar = mo.GetMethodParameters("SetGateways");
inPar["DefaultIPGateway"] = new string[] { DefaultIPGateway };
outPar = mo.InvokeMethod("SetGateways", inPar, null);
//设置DNS
inPar = mo.GetMethodParameters("SetDNSServerSearchOrder");
inPar["DNSServerSearchOrder"] = new string[] { DNS };
outPar = mo.InvokeMethod("SetDNSServerSearchOrder", inPar, null);
//设置MAC
MACHelper mh = new MACHelper();
mh.SetMACAddress(MAC);
break;
}
}
///
/// set
///
///
///
///
///
///
public static void SetNetworkAdapter(string ip,string subnetmask,string DefaultIPGateway,string DNS,string MAC)
{
ManagementBaseObject inPar = null;
ManagementBaseObject outPar = null;
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if (!(bool)mo["IPEnabled"])
continue;
//设置ip地址和子网掩码
inPar = mo.GetMethodParameters("EnableStatic");
inPar["IPAddress"] = new string[] { ip };
inPar["SubnetMask"] = new string[] { subnetmask };
outPar = mo.InvokeMethod("EnableStatic", inPar, null);
//设置网关地址
inPar = mo.GetMethodParameters("SetGateways");
inPar["DefaultIPGateway"] = new string[] { DefaultIPGateway };
outPar = mo.InvokeMethod("SetGateways", inPar, null);
//设置DNS
inPar = mo.GetMethodParameters("SetDNSServerSearchOrder");
inPar["DNSServerSearchOrder"] = new string[] { DNS };
outPar = mo.InvokeMethod("SetDNSServerSearchOrder", inPar, null);
//设置MAC
MACHelper mh = new MACHelper();
mh.SetMACAddress(MAC);
break;
}
}
///
/// 显示当前的ip 网卡 dns 等信息(IP,子网掩码,默认网关,DNS,MAC)
///
public static string[] ShowNetworkAdapterInfo()
{
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if (!(bool)mo["IPEnabled"])
continue;
//Console.WriteLine("{0}/n SVC: '{1}' MAC: [{2}]", (string)mo["Caption"],
// (string)mo["ServiceName"], (string)mo["MACAddress"]);
string[] addresses = (string[])mo["IPAddress"];
string[] subnets = (string[])mo["IPSubnet"];
string[] gateways = (string[])mo["DefaultIPGateway"];
string[] dnses = (string[])mo["DNSServerSearchOrder"];
string macs = mo["MacAddress"].ToString();
string[] ipandall = { addresses[0], subnets[0], gateways[0], dnses[0], macs };
return ipandall;
}
return null;
}
static PublicOper PO = new PublicOper();
public static string SetNetIPConfig(string ip,string mask,string gateway,string DNS)
{
string TmpCmd = "";
string lab = "";
string[] iPInfo = ShowNetworkAdapterInfo();
if (iPInfo[0].Trim() != ip.Trim() || iPInfo[1].Trim() != mask.Trim())
{
TmpCmd = "netsh -c interface ip set address name="本地连接" source=static addr=" + ip.Trim() + " mask=" + mask.Trim();
if (PO.RunCmd(TmpCmd).Length == 7)
{
System.Threading.Thread.Sleep(100);
}
else
{
lab += "IP或子网修改失败!";
System.Threading.Thread.Sleep(100);
return lab;
}
}
if (iPInfo[2].Trim() != gateway.Trim())
{
TmpCmd = "netsh -c interface ip set address name="本地连接" gateway=" + gateway.Trim() + " gwmetric=0";
if (PO.RunCmd(TmpCmd).Length == 7)
{
System.Threading.Thread.Sleep(100);
}
else
{
lab += "网关修改失败!";
System.Threading.Thread.Sleep(100);
return lab;
}
}
if (iPInfo[3].Trim() != DNS.Trim())
{
if (DNS.Trim().Length > 0)
{
TmpCmd = "netsh -c interface ip set dns name="本地连接" source=static addr=" + DNS.Trim() + " register=PRIMARY";
if (PO.RunCmd(TmpCmd).Length == 7)
{
System.Threading.Thread.Sleep(100);
}
else
{
lab += "DNS修改失败!";
System.Threading.Thread.Sleep(100);
return lab;
}
}
}
lab = "全部修改完毕!";
return lab;
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Data;
using System.Diagnostics;
namespace InsteadIP
{
class PublicOper
{
///
/// 公共操作类
///
public PublicOper()
{
}
#region 将Byte数组转换为String字符串
///
/// 将Byte数组转换为String字符串
///
/// 需要转换的Byte数组
/// 转换后的字符串
public string ByteArrayToStr(byte[] ByteArray)
{
string ret = ""; int IndexOf0 = 0;
if (ByteArray != null && ByteArray.Length > 0)
{
ret = System.Text.Encoding.Default.GetString(ByteArray);
IndexOf0 = ret.IndexOf('\0');
if (IndexOf0 >= 0 && ret.Length > 0)
ret = ret.Substring(0, IndexOf0).Trim();
}
return ret;
}
#endregion
#region 将String字符串转换为Byte数组
///
/// 将String字符串转换为Byte数组
///
/// 需要转换的String字符串
/// 转换后的Byte数组
public byte[] StringToByteArray(string str)
{
if (str != null)
return System.Text.Encoding.Default.GetBytes(str);
else
return null;
}
#endregion
#region 清空Text文本框内容
///
/// 清空Text文本框内容
///
/// 控件集合
public void ClearText(Control.ControlCollection Controls)
{
string mytext;
foreach (Control co in Controls)
{
mytext = co.GetType().ToString();
if (mytext == "System.Windows.Forms.TextBox")
((TextBox)co).Clear();
}
}
#endregion
#region 转换Text文本框中的单引号
///
/// 转换Text文本框中的单引号
///
/// 控件集合
public void ConvertText(Control.ControlCollection Controls)
{
string mytext;
foreach (Control co in Controls)
{
mytext = co.GetType().ToString();
if (mytext == "System.Windows.Forms.TextBox")
((TextBox)co).Text = ((TextBox)co).Text.Replace("'","");
}
}
#endregion
public string RunCmd(string command)
{
//實例一個Process類,啟動一個獨立進程
Process p = new Process();
//Process類有一個StartInfo屬性,這個是ProcessStartInfo類,
//包括了一些屬性和方法,下面我們用到了他的幾個屬性:
p.StartInfo.FileName = "cmd.exe"; //設定程序名
p.StartInfo.Arguments = "/c " + command; //設定程式執行參數
p.StartInfo.UseShellExecute = false; //關閉Shell的使用
p.StartInfo.RedirectStandardInput = true; //重定向標準輸入
p.StartInfo.RedirectStandardOutput = true; //重定向標準輸出
p.StartInfo.RedirectStandardError = true; //重定向錯誤輸出
p.StartInfo.CreateNoWindow = true; //設置不顯示窗口
p.Start(); //啟動
//p.StandardInput.WriteLine(command); //也可以用這種方式輸入要執行的命令
//p.StandardInput.WriteLine("exit"); //不過要記得加上Exit要不然下一行程式執行的時候會當機
return p.StandardOutput.ReadToEnd(); //從輸出流取得命令執行結果
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Win32;
using System.Net.NetworkInformation;
using System.Management;
using System.Threading;
using System.Runtime.InteropServices;
namespace DynamicMAC
{
public class MACHelper
{
[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(int Description, int ReservedValue);
///
/// 是否能连接上Internet
///
///
public bool IsConnectedToInternet()
{
int Desc = 0;
return InternetGetConnectedState(Desc, 0);
}
/////
///// 获取MAC地址
/////
//public string GetMACAddress()
//{
// //得到 MAC的注册表键
// RegistryKey macRegistry = Registry.LocalMachine.OpenSubKey("SYSTEM").OpenSubKey("CurrentControlSet").OpenSubKey("Control")
// .OpenSubKey("Class").OpenSubKey("{4D36E972-E325-11CE-BFC1-08002bE10318}");
// string[] ms = macRegistry.GetSubKeyNames();
// IList list = macRegistry.GetSubKeyNames().ToList();
// IPGlobalProperties computerProperties = IPGlobalProperties.GetIPGlobalProperties();
// NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
// var adapter = nics.First(o => o.Name == "本地连接");
// if (adapter == null)
// return null;
// return string.Empty;
//}
///
/// 设置MAC地址
///
///
public void SetMACAddress(string newMac)
{
string macAddress;
string index = GetAdapterIndex(out macAddress);
if (index == null)
return;
//得到 MAC的注册表键
RegistryKey macRegistry = Registry.LocalMachine.OpenSubKey("SYSTEM").OpenSubKey("CurrentControlSet").OpenSubKey("Control")
.OpenSubKey("Class").OpenSubKey("{4D36E972-E325-11CE-BFC1-08002bE10318}").OpenSubKey(index, true);
if (string.IsNullOrEmpty(newMac))
{
macRegistry.DeleteValue("NetworkAddress");
}
else
{
macRegistry.SetValue("NetworkAddress", newMac);
macRegistry.OpenSubKey("Ndi", true).OpenSubKey("params", true).OpenSubKey("NetworkAddress", true).SetValue("Default", newMac);
macRegistry.OpenSubKey("Ndi", true).OpenSubKey("params", true).OpenSubKey("NetworkAddress", true).SetValue("ParamDesc", "MAC");
}
//Thread oThread = new Thread(new ThreadStart(ReConnect));//new Thread to ReConnect
//oThread.Start();
}
///
/// 重设MAC地址
///
public void ResetMACAddress()
{
SetMACAddress(string.Empty);
}
///
/// 重新连接
///
//private void ReConnect()
//{
////NetSharingManagerClass netSharingMgr = new NetSharingManagerClass();
////INetSharingEveryConnectionCollection connections = netSharingMgr.EnumEveryConnection;
////foreach (INetConnection connection in connections)
////{
////INetConnectionProps connProps = netSharingMgr.get_NetConnectionProps(connection);
////if (connProps.MediaType == tagNETCON_MEDIATYPE.NCM_LAN)
////{
////connection.Disconnect(); //禁用网络
////connection.Connect(); //启用网络
////}
////}
//}
///
/// 生成随机MAC地址
///
///
public string CreateNewMacAddress()
{
//return "0016D3B5C493";
int min = 0;
int max = 16;
Random ro = new Random();
var sn = string.Format("{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}{11}",
ro.Next(min, max).ToString("x"),//0
ro.Next(min, max).ToString("x"),//
ro.Next(min, max).ToString("x"),
ro.Next(min, max).ToString("x"),
ro.Next(min, max).ToString("x"),
ro.Next(min, max).ToString("x"),//5
ro.Next(min, max).ToString("x"),
ro.Next(min, max).ToString("x"),
ro.Next(min, max).ToString("x"),
ro.Next(min, max).ToString("x"),
ro.Next(min, max).ToString("x"),//10
ro.Next(min, max).ToString("x")
).ToUpper();
return sn;
}
///
/// 得到Mac地址及注册表对应Index
///
///
///
public string GetAdapterIndex(out string macAddress)
{
ManagementClass oMClass = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection colMObj = oMClass.GetInstances();
macAddress = string.Empty;
int indexString = 1;
foreach (ManagementObject objMO in colMObj)
{
indexString++;
if (objMO["MacAddress"] != null && (bool)objMO["IPEnabled"] == true)
{
macAddress = objMO["MacAddress"].ToString().Replace(":", "");
break;
}
}
if (macAddress == string.Empty)
return null;
else
return indexString.ToString().PadLeft(4, '0');
}
//#region Temp
//public void noting()
//{
////ManagementClass oMClass = new ManagementClass("Win32_NetworkAdapterConfiguration");
//ManagementClass oMClass = new ManagementClass("Win32_NetworkAdapter");
//ManagementObjectCollection colMObj = oMClass.GetInstances();
//foreach (ManagementObject objMO in colMObj)
//{
//if (objMO["MacAddress"] != null)
//{
//if (objMO["Name"] != null)
//{
////objMO.InvokeMethod("Reset", null);
//objMO.InvokeMethod("Disable", null);//Vista only
//objMO.InvokeMethod("Enable", null);//Vista only
//}
////if ((bool)objMO["IPEnabled"] == true)
////{
//// //Console.WriteLine(objMO["MacAddress"].ToString());
//// //objMO.SetPropertyValue("MacAddress", CreateNewMacAddress());
//// //objMO["MacAddress"] = CreateNewMacAddress();
//// //objMO.InvokeMethod("Disable", null);
//// //objMO.InvokeMethod("Enable", null);
//// //objMO.Path.ReleaseDHCPLease();
//// var iObj = objMO.GetMethodParameters("EnableDHCP");
//// var oObj = objMO.InvokeMethod("ReleaseDHCPLease", null, null);
//// Thread.Sleep(100);
//// objMO.InvokeMethod("RenewDHCPLease", null, null);
////}
//}
//}
//}
//public void no()
//{
//Shell32.Folder networkConnectionsFolder = GetNetworkConnectionsFolder();
//if (networkConnectionsFolder == null)
//{
//Console.WriteLine("Network connections folder not found.");
//return;
//}
//Shell32.FolderItem2 networkConnection = GetNetworkConnection(networkConnectionsFolder, string.Empty);
//if (networkConnection == null)
//{
//Console.WriteLine("Network connection not found.");
//return;
//}
//Shell32.FolderItemVerb verb;
//try
//{
//IsNetworkConnectionEnabled(networkConnection, out verb);
//verb.DoIt();
//Thread.Sleep(1000);
//IsNetworkConnectionEnabled(networkConnection, out verb);
//verb.DoIt();
//}
//catch (ArgumentException ex)
//{
//Console.WriteLine(ex.Message);
//}
//}
/////
///// Gets the Network Connections folder in the control panel.
/////
///// The Folder for the Network Connections folder, or null if it was not found.
//static Shell32.Folder GetNetworkConnectionsFolder()
//{
//Shell32.Shell sh = new Shell32.Shell();
//Shell32.Folder controlPanel = sh.NameSpace(3); // Control panel
//Shell32.FolderItems items = controlPanel.Items();
//foreach (Shell32.FolderItem item in items)
//{
//if (item.Name == "网络连接")
//return (Shell32.Folder)item.GetFolder;
//}
//return null;
//}
/////
///// Gets the network connection with the specified name from the specified shell folder.
/////
///// The Network Connections folder.
///// The name of the network connection.
///// The FolderItem for the network connection, or null if it was not found.
//static Shell32.FolderItem2 GetNetworkConnection(Shell32.Folder networkConnectionsFolder, string connectionName)
//{
//Shell32.FolderItems items = networkConnectionsFolder.Items();
//foreach (Shell32.FolderItem2 item in items)
//{
//if (item.Name == "本地连接")
//{
//return item;
//}
//}
//return null;
//}
/////
///// Gets whether or not the network connection is enabled and the command to enable/disable it.
/////
///// The network connection to check.
///// On return, receives the verb used to enable or disable the connection.
///// True if the connection is enabled, false if it is disabled.
//static bool IsNetworkConnectionEnabled(Shell32.FolderItem2 networkConnection, out Shell32.FolderItemVerb enableDisableVerb)
//{
//Shell32.FolderItemVerbs verbs = networkConnection.Verbs();
//foreach (Shell32.FolderItemVerb verb in verbs)
//{
//if (verb.Name == "启用(&A)")
//{
//enableDisableVerb = verb;
//return false;
//}
//else if (verb.Name == "停用(&B)")
//{
//enableDisableVerb = verb;
//return true;
//}
//}
//throw new ArgumentException("No enable or disable verb found.");
//}
//#endregion
}
}
浙公网安备 33010602011771号