复制
代码 代码示例:private void ButtonIP_Click(object sender, System.EventArgs e){ System.Net.IPAddress[] addressList = Dns.GetHostByName(Dns.GetHostName()).AddressListif ( 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.Managementstring 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.NetTextIP.Text=Page.Request.UserHostAddress获取客户端本机的MAC地址刚复杂一些,需要调用两个API,用ARP协议获取,但也只能获取到同网段机器的MAC,对于跨网段的得利用IP扫描或cmd中nBTstat命令获取MAC地址。获取服务器电脑名: Page.Server.ManchineName获取用户信息: Page.User获取客户端电脑名:Page.Request.UserHostName获取客户端电脑IP: Page.Request.UserHostAddress2. 在网络编程中的通用方法:获取当前电脑名: static System.Net.Dns.GetHostName()根据电脑名取出全部IP地址: static System.Net.Dns.Resolve(电脑名).AddressList也可根据IP地址取出电脑名: static System.Net.Dns.Resolve(IP地址).HostName3. 系统环境类的通用属性:asp.net中获取客户端ip地址的两种方法
方法一:
/// <summary>
/// 获取用户登录IP
/// </summary>
/// <returns></returns>
string GetIp()
{
//可以透过代理服务器
string userIP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"]
if (userIP == null || userIP == "")
{
//没有代理服务器,如果有代理服务器获取的是代理服务器的IP
userIP = Request.ServerVariables["REMOTE_ADDR"]
}
return userIP
}
方法二:(很抱歉,这种方法获取的是服务器端的IP)
//需要using System.Net
string hostname = Dns.GetHostName()//服务器的用户名
Response.Write("HostName:"+hostname)
IPAddress[] address = Dns.GetHostAddresses(hostname)//获取服务器端IP列表,第一IP是address[0]
IPEndPoint ipendpoint = new IPEndPoint(address[0], 1234)
Response.Write("address:"+ipendpoint.Address.ToString())//输出IP:192.168.0.210,不是127.0.0.1
Response.Write("port:" + ipendpoint.Port.ToString())//输出1234
Response.Write("endpoint:" + ipendpoint.ToString())//输出的是192.168.0.210:1234
评论列表(0条)