获取本机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目录下,如果没有你可以在本地电脑搜搜,在没有就到网上下载

posted @ 2012-10-11 16:57  孤狼灬  阅读(365)  评论(1编辑  收藏  举报