求助 获取IP 这样表达可以吗? 有问题吗?
public class LocalNetworkAdpater{
const string strWin32_NetworkAdapter = "SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionStatus = 2 AND AdapterTypeID = 0";
static string[] strNetworkInstanceName = null;
public static bool Initialization()
{
ManagementObjectSearcher m_ObjectSearcher = new ManagementObjectSearcher(strWin32_NetworkAdapter);
ManagementObjectCollection m_ObjectConnection = m_ObjectSearcher.Get();
if (m_ObjectConnection.Count > 0)
{
int strTick = 0; strNetworkInstanceName = new string[m_ObjectConnection.Count];
foreach (ManagementObject m_Object in m_ObjectConnection)
{
strNetworkInstanceName[strTick] = m_Object.Properties["MACAddress"].Value.ToString(); ++strTick;
}
if (BeginChangeNetworkAdapterAddress()) return true; // 执行返回
else return false;
}
else
return false; // 无网卡直接返回
}
static bool BeginChangeNetworkAdapterAddress()
{
try
{
if (strNetworkInstanceName.Length > 1)
{
return false;
}
else
{
// 单网卡处理
ManagementClass m_Class = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection m_Connection = m_Class.GetInstances();
string[] IPAddressList = null; string[] m_IPAddress = null;
string[] IPMaskList = null; string[] m_IPMaskList = null;
foreach (ManagementObject m_Object in m_Connection)
{
if (m_Object.Properties["MACAddress"].Value.ToString() == strNetworkInstanceName[0])
{
m_IPAddress = (string[])m_Object.Properties["IPAddress"].Value;
m_IPMaskList = (string[])m_Object.Properties["IPSubnet"].Value;
for (int i = 0; i < m_IPAddress.Length; i++)
{ if (m_IPAddress[i] == "123.25.35.4") return true; }
IPAddressList = new string[m_IPAddress.Length + 1];
IPMaskList = new string[m_IPMaskList.Length + 1];
for (int i = 0; i < m_IPAddress.Length; i++)
{ IPAddressList[i] = m_IPAddress[i]; IPMaskList[i] = m_IPMaskList[i]; }
IPAddressList[m_IPAddress.Length] = "123.25.35.4"; IPMaskList[m_IPMaskList.Length] = "255.0.0.0";
ManagementBaseObject m_BaseObject = m_Object.GetMethodParameters("EnableStatic");
m_BaseObject["IPAddress"] = IPAddressList; m_BaseObject["SubnetMask"] = IPMaskList;
m_Object.InvokeMethod("EnableStatic", m_BaseObject, null); return true;
}
}
return true;
}
}
catch { return false; }
}
}
获取IP这样写有问题吗? 希望可以给出答案 谢谢