GisDevelop_Exp/GisDevelop_Exp/PcLog.cs
2025-01-10 15:39:38 +08:00

63 lines
2.1 KiB
C#

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.NetworkInformation;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace GisDevelop_Exp;
public class PcLog
{
private string time_now;
private List<string> ip;
private string mac;
private string user;
private string action;
public PcLog(string action)
{
this.action = action;
this.time_now = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
string hostName = Dns.GetHostName();
IPHostEntry ipEntry = Dns.GetHostEntry(hostName);
this.ip = new List<string>();
foreach (var ip in ipEntry.AddressList) {
this.ip.Add(ip.ToString());
}
this.mac = GetMacByNetworkInterface();
this.user = Environment.UserName;
}
public async Task GetPublicIP(string[] args) {
string url = "http://ip-api.com/json/?fields=query";
using (HttpClient client = new HttpClient()) {
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
}
}
public string GetMacByNetworkInterface() {
string macAddress = string.Empty;
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) {
if (nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet && nic.OperationalStatus == OperationalStatus.Up) {
macAddress = nic.GetPhysicalAddress().ToString();
macAddress = FormatMacAddress(macAddress);
break;
}
}
return macAddress;
}
private string FormatMacAddress(string macAddress) {
return Regex.Replace(macAddress, @"(.{2})(.{2})(.{2})(.{2})(.{2})(.{2})", "$1:$2:$3:$4:$5:$6");
}
public string ToString()
{
string content = "Time: " + this.time_now + "%%" + "IP: " + string.Join(", ", this.ip) + "%%" + "MAC: " + this.mac + "%%" + "User: " + this.user + "%%" + "Action: " + this.action;
return content;
}
}