使用c#在消息框中获取MAC地址 [英] get MAC address in message box using c#

查看:64
本文介绍了使用c#在消息框中获取MAC地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用c#获取我的电脑的MAC地址?我想在消息框中打印我的MAC地址...请帮帮我..



拼写[/ edit]

how can i get my pc's MAC address using c#? i want to print my MAC address in message box... please help me..

[edit] Spelling [/edit]

推荐答案

如果您的意思是MAC地址,那么:



If you mean MAC address, then:

/// <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;
    }

然后你可以使用ToString来显示地址:

You can then just use ToString to display the address:

MessageBox.Show(GetMacAddress().ToString());


我在那里添加了一些调整,并对OriginalGriff充满了敬意。这将确保:

1.当前连接的适配器被选中;

2.即使是已连接,也不会考虑所有虚拟和伪适配器。

3.确保没有附加Null或空MAC。



I added a little tweak in there with all due respect to OriginalGriff. This will ensure that:
1. The Adapter that is currently connected is Picked;
2. All Virtual and Pseudo Adapters will not be considered even though the are "Connected".
3. Ensure that No Null or Empty MAC is Appended.

string mac = "";
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
            {

                if (nic.OperationalStatus == OperationalStatus.Up && (!nic.Description.Contains("Virtual") && !nic.Description.Contains("Pseudo")))
                {
                    if (nic.GetPhysicalAddress().ToString() != "")
                    {
                        mac = nic.GetPhysicalAddress().ToString();
                    }
                }
            }
MessageBox.Show(mac);


来自系统。网名称空间:



From System.Net namespace:

public string GetMACAddress()
{
    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;
}


这篇关于使用c#在消息框中获取MAC地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆