C#獲取本機IP地址和Mac地址的方法
更新時間:2015年05月06日 11:50:15 作者:niuniu
這篇文章主要介紹了C#獲取本機IP地址和Mac地址的方法,實例分析了C#網(wǎng)絡(luò)功能的基本技巧,需要的朋友可以參考下
本文實例講述了C#獲取本機IP地址和Mac地址的方法。分享給大家供大家參考。具體分析如下:
查找了幾個方法,經(jīng)過調(diào)試修改,下面這個方法能很好的獲取到本地的IP和MAC地址??梢杂糜谶@方面的功能實現(xiàn)。主要是要添加System.Management的引用。
using System;
using System.Management;
using System.Net;
public class Program
{
static void Main(string[] args)
{
try
{
string ip = "";
string mac = "";
ManagementClass mc;
string hostInfo = Dns.GetHostName();
//IP地址
//System.Net.IPAddress[] addressList = Dns.GetHostByName(Dns.GetHostName()).AddressList;這個過時
System.Net.IPAddress[] addressList = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
for (int i = 0; i < addressList.Length; i++)
{
ip = addressList[i].ToString();
}
//mac地址
mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if (mo["IPEnabled"].ToString() == "True")
{
mac = mo["MacAddress"].ToString();
}
}
//輸出
string outPutStr = "IP:{0},\n MAC地址:{1}";
outPutStr = string.Format(outPutStr, ip, mac);
Console.WriteLine(outPutStr);
}
catch (Exception e)
{ }
Console.ReadLine();
}
}
希望本文所述對大家的C#程序設(shè)計有所幫助。
您可能感興趣的文章:
相關(guān)文章
C#實現(xiàn)根據(jù)指定容器和控件名字獲得控件的方法
這篇文章主要介紹了C#實現(xiàn)根據(jù)指定容器和控件名字獲得控件的方法,其中包括了遍歷與遞歸的應(yīng)用,需要的朋友可以參考下2014-08-08
C#簡單訪問SQLite數(shù)據(jù)庫的方法(安裝,連接,查詢等)
這篇文章主要介紹了C#簡單訪問SQLite數(shù)據(jù)庫的方法,涉及SQLite數(shù)據(jù)庫的下載、安裝及使用C#連接、查詢SQLIte數(shù)據(jù)庫的相關(guān)技巧,需要的朋友可以參考下2016-07-07

