您的位置:首页 > 编程语言 > C#

C#中获取 IP、MAC等信息实例

2010-08-16 18:20 525 查看
项目中要求或许当前主机的IP和MAC等信息,参考网络上的帖子,重新整理下,直接贴代码:

namespace Iaspec.JWPGIS.Application.LogInfos
{
public class LogInfos
{
LogInfo logInfo;
public LogInfos()
{
this.logInfo = new LogInfo();
}

private string IPAddress = "";
private string MacAddress = "";
private string UserName = "";
private DateTime currentTime = DateTime.Now;
private LogType logType;
public LogType LogType
{
get { return logType; }
set { logType = value; }
}

string hostName = Dns.GetHostName();

/// <summary>
/// 获取当前主机IP地址
/// </summary>
public void GetHostIPAddress()
{
IPAddress[] addressList = Dns.GetHostEntry(this.hostName).AddressList;

if (addressList == null || addressList.Length == 0)
return;

for (int i = 0; i < addressList.Length; i++)
{
this.IPAddress += addressList[i].ToString();
}
}

/// <summary>
/// 获取当前主机Mac地址
/// </summary>
public void GetHostMacAddress()
{
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if (mo["IPEnabled"].ToString() == "True")
this.MacAddress = mo["MacAddress"].ToString();
}
}

/// <summary>
/// 获取当前用户名
/// </summary>
public void GetCurrentUser()
{
if (UserCookie.Instance.LoginUserInfo.UserName != null && UserCookie.Instance.LoginUserInfo.UserName != "")
this.UserName = UserCookie.Instance.LoginUserInfo.UserName;
}

/// <summary>
/// 获取创建时间
/// </summary>
public void GetCurrentTime()
{
this.currentTime = DateTime.Now;
}

public void SaveLog(LogType logType)
{
this.GetCurrentUser();
this.GetCurrentTime();
this.GetHostIPAddress();
this.GetHostMacAddress();

if (this.UserName == null || this.UserName == "")
return;

this.logInfo.UserName = this.UserName;
this.logInfo.CreateDate = this.currentTime;
this.logInfo.IP = this.IPAddress;
this.logInfo.MacAddress = this.MacAddress;
this.logInfo.LogType = (logType == LogType.Login) ? 0 : 1;

BusinessProxy.SaveLogFile(this.logInfo);
}
}
}

红色部分代码即是。当然,这里还可以获取host的其他的一些信息,具体参考MSDN.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: