获取本机mac和Ip地址

using System;

using System.Collections.Generic;

using System.Linq; using System.Text;

using System.Runtime.InteropServices;

using System.Net;

namespace getMac

{

     public static class Class1

    {

        //获取mac地址

        public static string getMyMac()

        {

            string ip = GetIP(); //本机ip地址

            int dest = inet_addr(ip);

            int num2 = inet_addr("");

            long mac = 0L;

            int length = 6;

            int num5 = SendARP(dest, 0, ref mac, ref length); //1.目标IP地址 2.源IP地址 3.返回MAC地址指针 4.返回MAC地址长度

            string str2 = mac.ToString("X"); //转换成十六进制

            if (str2 == "0")

            {

                return "Localhost";

            }

            while (str2.Length < 12)

            {

                str2 = str2.Insert(0, "0");

            }

            string str3 = "";

            for (int i = 0; i < 11; i++)

            {

                if ((i % 2) == 0)

                {

                    if (i == 0)

                    {

                        str3 = str3.Insert(0, str2.Substring(i, 2));

                    }

                    else

                    {

                        str3 = str3.Insert(0, str2.Substring(i, 2) + ":");

                    }

                }

            }

            return str3;

        }

        private static string GetIP()   //获取本地IP

        {

            IPHostEntry ipHost = Dns.Resolve(Dns.GetHostName());

            IPAddress ipAddr = ipHost.AddressList[0];

            return ipAddr.ToString();

        }

        [DllImport("Ws2_32.dll")]

        private static extern int inet_addr(string ip);

        [DllImport("Iphlpapi.dll")]

        private static extern int SendARP(int dest, int host, ref long mac, ref int length);

    }

}

 

//别忘了在bin目录下放入Ws2_32.dll和Iphlpapi.dll,一般这两个控件在本地电脑的C:\WINDOWS\system32目录下,如果没有你可以在本地电脑搜搜,在没有就到网上下载

转载于:https://www.cnblogs.com/hpp3501/archive/2012/10/11/2720192.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值