2012年5月11日 星期五
64位系统下,利用c#获取ipv4的DNS
inPar = null; outPar = null; mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); moc = mc.GetInstances(); foreach (ManagementObject mo in moc) { if (Convert.ToBoolean(mo["ipEnabled"])) { // 獲取Ip,子網掩碼,網關 ipAddress = (mo["IPAddress"] as string[])[0]; ipSubNet = (mo["IPSubnet"] as string[])[0]; ipGateway = (mo["DefaultIPGateway"] as string[])[0]; // 判斷DNS數量,並取值 int dnsCount = (mo["DNSServerSearchOrder"] as string[]).Length; if (dnsCount > 0) { firstDns = (mo["DNSServerSearchOrder"] as string[])[0]; } if (dnsCount > 1) { secondDns = (mo["DNSServerSearchOrder"] as string[])[1]; } break; } }
================================================================================================
獲取本機ip本來是很容易的,IPAddress _ip = Dns.GetHostAddresses(Dns.GetHostName())[0];就行了
但是在vista win7等系統裡面這樣獲得的是ipv6地址,另外有多張網卡的時候問題就更複雜了
以前我都是根據自己的ip修改數組的下標,不過那樣畢竟不是好的辦法,用AddressFamily來判斷更好
以下是我自己查msdn寫出來的,思路就是先用GetHostAddresses獲得所有ip地址,然後找出ipv4地址,儲存在StringCollection裡面。當然如果只是想獲取第一個ip就不用寫這麼麻煩。
using System;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Collections.Specialized;
namespace GetIpv4Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
ShowIP();
}
void ShowIP()
{
//ipv4地址也可能不止一個
foreach(string ip in GetLocalIpv4())
{
this.richTextBoxIPv4.AppendText(ip.ToString());
}
return;
}
string[] GetLocalIpv4()
{
//事先不知道ip的個數,數組長度未知,因此用StringCollection儲存
try
{
IPAddress[] localIPs;
localIPs = Dns.GetHostAddresses(Dns.GetHostName());
StringCollection IpCollection = new StringCollection();
foreach (IPAddress ip in localIPs)
{
//根據AddressFamily判斷是否為ipv4,如果是InterNetWork則為ipv6
if (ip.AddressFamily == AddressFamily.InterNetwork)
IpCollection.Add(ip.ToString());
}
string[] IpArray = new string[IpCollection.Count];
IpCollection.CopyTo(IpArray, 0);
return IpArray;
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
return null;
}
}
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言