NET获取IP等信息
1. 在ASP.NET中专用属性:
获取服务器电脑名:Page.Server.ManchineName
获取用户信息:Page.User
获取客户端电脑名:Page.Request.UserHostName
获取客户端电脑IP:Page.Request.UserHostAddress
2. 在网络编程中的通用方法:
获取当前电脑名:static System.Net.Dns.GetHostName()
根据电脑名取出全部IP地址:static System.Net.Dns.Resolve(电脑名).AddressList
也可根据IP地址取出电脑名:static System.Net.Dns.Resolve(IP地址).HostName
3. 系统环境类的通用属性:
当前电脑名:static System.Environment.MachineName
当前电脑所属网域:static System.Environment.UserDomainName
当前电脑用户:static System.Environment.UserName
获取真实IP
{
string ip;
try
{
HttpRequest request = HttpContext.Current.Request;
if (request.ServerVariables["HTTP_VIA"] != null)
{
ip = request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString().Split(',')[0].Trim();
}
else
{
ip = request.UserHostAddress;
}
}
catch (Exception e)
{
throw e;
}
return ip;
}
获取代理IP
{
string viaIp = null;
try
{
HttpRequest request = HttpContext.Current.Request;
if (request.ServerVariables["HTTP_VIA"] != null)
{
viaIp = request.UserHostAddress;
}
}
catch (Exception e)
{
throw e;
}
return viaIp;
获取服务器的IP地址方法以DNS法较为简单实用,如下:
using System.Net;
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();
}
}