可直接在控制台程序输出:
using System;
using System.Net;
class Program
{
static void Main()
{
// 获取本机IP地址
string ipAddress = GetLocalIPAddress();
Console.WriteLine("本机IP地址: " + ipAddress);
// 获取计算机名称
string computerName = Environment.MachineName;
Console.WriteLine("计算机名称: " + computerName);
// 获取登录用户名
string userName = Environment.UserName;
Console.WriteLine("登录用户名: " + userName);
Console.ReadLine();
}
static string GetLocalIPAddress()
{
string ipAddress = "";
IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
ipAddress = ip.ToString();
break;
}
}
return ipAddress;
}
}
【备注】以上是获取IPV4的方法,如需获取IPV6,将if条件改为:
//InterNetwork改为InterNetworkV6
if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)