C#得到当前计算机ip和计算机名
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Management;
using System.Net;
using System.Windows.Forms;
#region //獲取當前操作的主機名
public string GetHostName()
{
return System.Net.Dns.GetHostName();
}
#endregion
#region //取得當前操作主機的IP地址
public string GetHostIP()
{
string stringIP = "";
System.Net.IPAddress[] addresslist = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
stringIP = addresslist[0].ToString();
return stringIP;
}
#endregion
//得到电脑ip
public static string GetIPAddress()
{
string user_IP = string.Empty;
user_IP = System.Web.HttpContext.Current.Request.UserHostAddress;
return user_IP;
}
C#获取电脑名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
举例子来说明:
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 = "没有可用的连接";
}
}
获取服务器电脑名:page.server.manchinename
获取用户信息:page.user
获取客户端电脑名:page.request.userhostname
获取客户端电脑ip:page.request.userhostaddress