最近在看網路編程(主要是TCP/IP通訊的)的內容,還研究了下WMI。把獲得IP地址的方法總結如下。1. 使用ipconfig程式。在命令列下使用命令ipconfig可以得到原生每個有效網羅介面的IP網絡資訊。如果在代碼中,可以使用Process.Start()方法來調用ipconfig,然後使用Regex來解析結果──當然這樣做太繁了,不實用。但我曾經使用類似的方法在代碼中獲得MAC地址。2. 尋找註冊表。使用註冊表的麻煩之處在於各個版本的Windows在不同的地方存放網絡資訊。
Windows98&Windows Me註冊表中的位置為: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Class\NetTrans在這下面,每個Key對應一個網路裝置的資訊(IPAddress,DefaultGateway,IPMask)。
Windows NT
,
Windows 2000&Windows XP 和Windows98,Me不同,先要得知有哪些網卡,然後再查此網卡的網絡資訊。第一步:找到網卡,地址為:HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\NetworkCards,從中得到ServiceName值;第二步:根據上面得到的ServiceName值到下面地址尋找:HKEY_LOCAL_MACHINE\CurrentControlSet\Services,找到響應的Key後,在parameters\tcpip下可以得到網路裝置的資訊(IPAddress,DefaultGateway,IPMask)。另外,對於動態IP地址,可能得去尋找DHCPIPAddress註冊表對應關鍵詞的值。3. 使用WMI。查詢表Win32_NetworkAdapterConfiguration即可獲得。4. 使用DNS。
代碼如下:using System;
using Microsoft.Win32;
using System.Management;
using System.Net;
namespace IPAddress
{
class MainClass
{
/**//// <summary>
/// 應用程式的主進入點。
/// </summary>
[STAThread]
static void Main(string[] args)
{
GetIPByRegistry();
GetIPByWMI();
GetIPByDns();
Console.ReadLine();
}
Methods#region Methods
private const string CARDKEY = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkCards";
private const string SERVICEKEY = @"SYSTEM\CurrentControlSet\Services\";
public static void GetIPByRegistry()
{
RegistryKey entry = Registry.LocalMachine;
RegistryKey services = entry.OpenSubKey(CARDKEY);
if ( services == null)
return;
string[] cards = services.GetSubKeyNames();
services.Close();
foreach (string key in cards )
{
RegistryKey cardService = entry.OpenSubKey(CARDKEY + "\\" +key);
if ( cardService == null )
return;
string serviceName = cardService.GetValue("ServiceName").ToString();
Console.WriteLine("\n Network card : {0}",serviceName);
RegistryKey networkCard = entry.OpenSubKey(SERVICEKEY+serviceName+"\\Parameters\\Tcpip");
if ( networkCard != null )
{
string[] ips = (string[]) networkCard.GetValue("IPAddress");
foreach ( string ip in ips)
{
Console.WriteLine(" The IPAddress is :{0}",ip);
}
networkCard.Close();
}
entry.Close();
}
}
public static void GetIPByWMI()
{
string query = "select IPAddress from Win32_NetworkAdapterConfiguration where IPEnabled='TRUE'";
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection collection = searcher.Get();
foreach ( ManagementObject mo in collection )
{
string[] ips = (string[])mo["IPAddress"];
foreach ( string ip in ips )
{
Console.WriteLine(" Network card ip is :{0}",ip);
}
}
}
public static void GetIPByDns()
{
System.Net.IPAddress[] ips = Dns.GetHostByName(Dns.GetHostName()).AddressList;
foreach ( System.Net.IPAddress ip in ips )
{
Console.WriteLine("The ip is : {0}",ip.ToString());
}
}
#endregion
}
}