獲取服務器的IP地址方法以DNS法較為簡單實用,如下:
private void ButtonIP_Click(object sender, System.EventArgs e)
{ System.Net.IPAddress[] addressList = Dns.GetHostByName(Dns.GetHostName()).AddressList;
if ( addressList.Length>1)
{ TextLIP.Text = addressList[0].ToString();
TextSIP.Text = addressList[1].ToString();
}
else
{
TextLIP.Text = addressList[0].ToString();
TextSIP.Text = "沒有可用的連接";
}
}
獲取服務器的IP地址與MAC地址另一方法如下:
using System.Management;
string stringMAC = "";
string stringIP = "";
ManagementClass MC = new ManagementClass "Win32_NetworkAdapterConfiguration");
ManagementObjectCollection MOC= MC.GetInstances();
foreach(ManagementObject MO in MOC)
{
if ((bool)MO["IPEnabled"] == true)
{
stringMAC += MO["MACAddress"].ToString();
TextMAC.Text = stringMAC.ToString();
string[] IPAddresses = (string[]) MO["IPAddress"];
if(IPAddresses.Length > 0)
stringIP = IPAddresses[0];
TextIP.Text = stringIP.ToString();
}
}
獲取客戶端本機的IP地址相當簡易,方法如下:
using System.Net;
TextIP.Text=Page.Request.UserHostAddress;
如要獲取客戶端本機的MAC地址就相對復雜些,得導入調用兩個API,用ARP協議獲取,但這樣只能獲取到同網段機器的MAC,對於跨網段的得利用IP掃描或cmd中nbtstat命令獲取MAC地址。也可通過讀取系統注冊表值或WMI的數據庫來獲取。各位如有簡易可行的好辦法請留言告訴我。