@manhng

Welcome to my blog!

Get MAC Address + Internet Connectivity

January 17, 2020 15:32

Get MAC Address + Internet Connectivity (edit)

Bài toán:

  • Bạn cần kiểm tra kết nối Internet và lấy MAC Address
  • Bạn cần biết trạng thái máy bạn đã join Domain chưa?
  • Ngoài ra bạn cần biết đường dẫn của chương trình đang mở?

Bài viết này dành cho bạn!

  • Thư viện: System.Management.dll
  • Đường dẫn: C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.Management.dll

Cách dùng:

using System;

namespace ConsoleApp10
{
internal class Program
{
private static void Main(string[] args)
{
//
// Internet connection
//var isConnectedToInternet = Utils.CheckConnectivity("www.google.com");

var isConnectedToInternet = Utils.CheckForInternetConnection();

if (isConnectedToInternet)
{
Console.WriteLine("Connected to Internet");
}
else
{
Console.WriteLine("Not connected to Internet");
}

//
// MAC Address
var physicalAddress = Utils.GetMacAddressInString();
Console.WriteLine(physicalAddress.ToString());

//
// Is Domain Joined
string domainName = "MyDomainName";
var isDomainJoined = Utils.IsDomainJoined(out domainName);
Console.WriteLine("IsDomainJoined: " + isDomainJoined.ToString());

//
// Get Physical Path of the Running Program by PID
int pid = 7152;
var filePath = Utils.GetProcessFilepath(pid);
Console.WriteLine(filePath);
}
}
}

Code samples

using System;
using System.Diagnostics;
using System.Management;
using System.Net;
using System.Net.NetworkInformation;

namespace ConsoleApp10
{
public static class Utils
{
public static string GoogleGenerate204 = "http://google.com/generate_204";

/// <summary>
/// https://docs.microsoft.com/en-us/dotnet/api/system.net.networkinformation.physicaladdress?view=netframework-4.5
/// </summary>
/// <returns></returns>
public static bool CheckForInternetConnection()
{
try
{
using (var client = new WebClient())
using (client.OpenRead(GoogleGenerate204))
{
return true;
}
}
catch
{
return false;
}
}

/// <summary>
/// https://docs.microsoft.com/en-us/dotnet/api/system.net.networkinformation.physicaladdress?view=netframework-4.5
/// </summary>
/// <param name="ipAddress"></param>
/// <returns></returns>
public static bool CheckConnectivity(string ipAddress)
{
bool connectionExists = false;
try
{
System.Net.NetworkInformation.Ping pingSender = new System.Net.NetworkInformation.Ping();
System.Net.NetworkInformation.PingOptions options = new System.Net.NetworkInformation.PingOptions();
options.DontFragment = true;
if (!string.IsNullOrEmpty(ipAddress))
{
System.Net.NetworkInformation.PingReply reply = pingSender.Send(ipAddress);
connectionExists = reply.Status == System.Net.NetworkInformation.IPStatus.Success ? true : false;
}
}
catch (PingException ex)
{
Debug.WriteLine(ex.ToString());
}
return connectionExists;
}

/// <summary>
/// Gets the MAC address of the current PC.
/// </summary>
/// <returns></returns>
public static PhysicalAddress GetMacAddress()
{
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
// Only consider Ethernet network interfaces
if (nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet &&
nic.OperationalStatus == OperationalStatus.Up)
{
return nic.GetPhysicalAddress();
}
}
return null;
}

/// <summary>
/// Gets the MAC address of the current PC.
/// </summary>
/// <returns></returns>
public static string GetMacAddressInString()
{
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
String sMacAddress = string.Empty;
foreach (NetworkInterface adapter in nics)
{
if (sMacAddress == String.Empty) // only return MAC Address from first card
{
IPInterfaceProperties properties = adapter.GetIPProperties();
sMacAddress = adapter.GetPhysicalAddress().ToString();
}
}
return sMacAddress;
}

/// <summary>
/// Input: 7152 ~ Process ID of Visual Studio 2017
/// Output: C:\Program Files(x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\devenv.exe
/// </summary>
/// <param name="processId"></param>
/// <returns></returns>
public static string GetProcessFilepath(int processId)
{
string wmiQueryString = "SELECT ProcessId, ExecutablePath FROM Win32_Process WHERE ProcessId = " + processId;
using (var searcher = new ManagementObjectSearcher(wmiQueryString))
{
using (ManagementObjectCollection results = searcher.Get())
{
foreach (ManagementObject mo in results)
{
return (string)mo["ExecutablePath"];
}
}
}
return null;
}

/// <summary>
///
/// </summary>
/// <param name="processId"></param>
/// <returns></returns>
public static string GetMainModuleFilepath(int processId)
{
string wmiQueryString = "SELECT ProcessId, ExecutablePath FROM Win32_Process WHERE ProcessId = " + processId;

using (var searcher = new ManagementObjectSearcher(wmiQueryString))
{
if (searcher != null) // seen it return null
{
using (var results = searcher.Get())
{
if (results != null)
{
foreach (ManagementObject mo in results)
{
if (mo != null)
{
return (string)mo["ExecutablePath"];
}
}
}
}
}
}
return null;
}

/// <summary>
/// https://www.csharpcodi.com/csharp-examples/System.Management.ManagementObjectSearcher.Get()/
/// </summary>
/// <param name="domainName"></param>
/// <returns></returns>
public static bool IsDomainJoined(out string domainName)
{
try
{
var query = new SelectQuery("Win32_ComputerSystem");

using (var searcher = new
ManagementObjectSearcher(query))
{
foreach (var o in searcher.Get())
{
var mo = (ManagementObject)o;
if ((bool)mo["partofdomain"] != true)
{
domainName = mo["workgroup"] as string;
return false;
}
else
{
domainName = mo["domain"] as string;
return true;
}
}
}

domainName = null;
return false;
}
catch (Exception ex)
{
throw new Exception("Exception in IsDomainJoined() : " + ex.Message);
}
}
}
}

Categories