C#获取本机IP

[DllImport("Iphlpapi.dll")]
private static extern int SendARP(Int32 dest, Int32 host,
 ref Int64 mac, ref Int32 length);
[DllImport("Ws2_32.dll")]
private static extern Int32 inet_addr(string ip);
public string getLocalIP()
{
      string strHostName = Dns.GetHostName(); //得到本机的主机名
       IPHostEntry ipEntry = Dns.GetHostByName(strHostName); //取得本机IP
      string strAddr = ipEntry.AddressList[0].ToString();
      return (strAddr);
}

_________________________________________________________

原文

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Management;

namespace exp_01_1021
{
class Program
{
static void Main(string[] args)
{
getHostInfo HostInfo = new getHostInfo();
string IP = HostInfo.getIP();
string Mac = HostInfo.getMac();
Console.WriteLine("Local IP: {0}", IP);
Console.WriteLine("MacAddress: {0}", Mac);
Console.ReadLine();
}
}
class getHostInfo
{
public string getIP() //获取IP
{
string HostName = Dns.GetHostName(); //得到主机名
IPHostEntry IpEntry = Dns.GetHostEntry(HostName); //得到主机IP
string strIPAddr = IpEntry.AddressList[0].ToString();
return (strIPAddr);
}
public string getMac() //获取Mac
{
string MacAddr = null;
ManagementObjectSearcher Query = new ManagementObjectSearcher

("select*fromWin32_NetworkAdapterConfiguration");
ManagementObjectCollection QueryCollection= Query.Get();
foreach (ManagementObject mo in QueryCollection)
{
if (mo["IPEnabled"].ToString() =="True")
MacAddr = mo["MacAddress"].ToString();
}
return (MacAddr);
}
}
}

//getIP类部分使用了两个类:Dns、IPHostEntry(在命名空间System.Net中).
//Dns类:主要是从域名系统(DNS)中检索关于特定主机的信息.
//IPHostEntry类则将一个域名系统或主机名与一组IP地址相关联,它与DNS类一起使用,用于获取主机的IP地址组.

//getMac类部分使用了两个类:ManagementObjectSearcher、ManagementObjectCollection.
//在获取本机的MAC地址时,可以使用WMI规范,通过SELECT语句提取MAC地址.在.NET框架中,WMI规范的实现定义在System.Management命名空间中.
//ManagementObjectSearcher类用于根据指定的查询检索管理对象的集合.
//ManagementObjectCollection类为管理对象的集合,上例中由检索对象返回管理对象集合赋值给它.