程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#獲取局域網內IP的MAC

C#獲取局域網內IP的MAC

編輯:C#入門知識

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Runtime.InteropServices;
using System.Net;

namespace MacApp
{
    public partial class Form1 : Form
    {
        [DllImport("ws2_32.dll")]
        private static extern int inet_addr(string cp);
        [DllImport("IPHLPAPI.dll")]
        private static extern int SendARP(Int32 DestIP, Int32 SrcIP, ref Int64 pMacAddr, ref Int32 PhyAddrLen);
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            richTextBox1.Text = GetMacAddress(textBox1.Text);//獲取遠程IP(不能跨網段)的MAC地址
        }
        private string GetMacAddress(string hostip)//獲取遠程IP(不能跨網段)的MAC地址
        {
            string Mac = "";
            try
            {
                Int32 ldest = inet_addr(hostip); //將IP地址從 點數格式轉換成無符號長整型
                Int64 macinfo = new Int64();
                Int32 len = 6;
                SendARP(ldest, 0, ref macinfo, ref len);
                string TmpMac = Convert.ToString(macinfo, 16).PadLeft(12,0);//轉換成16進制  注意有些沒有十二位
                Mac = TmpMac.Substring(0, 2).ToUpper();//
                for (int i = 2; i < TmpMac.Length; i = i + 2)
                {
                    Mac = TmpMac.Substring(i, 2).ToUpper() +"-"+ Mac;
                }
            }
            catch (Exception Mye)
            {
                Mac = "獲取遠程主機的MAC錯誤:" + Mye.Message;
            }
            return Mac;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            if (Dns.GetHostEntry(Dns.GetHostName()).AddressList.Length > 0)
            {
                textBox1.Text= Dns.GetHostEntry(Dns.GetHostName()).AddressList[0].ToString();//獲取本機IP地址
            }
        }
    }
}

    

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved