본문 바로가기

자료

[VB.NET/C#] Network MacAddress

728x90

[VB.NET/C#] Network MacAddress


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

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

namespace CSharp_MacAddress
{
    public partial class Form1 : Form
    {
        [DllImport("iphlpapi.dll", ExactSpelling = true)]
        private static extern int SendARP(int destinationIPValue, int sourceIPValue, byte[] physicalAddressArray, ref uint physicalAddresArrayLength);

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string strMacAddress = Get_MACAddress("192.168.0.6");

            MessageBox.Show(strMacAddress);

        }

        public string Get_MACAddress(string strIPAddress)
        {
            IPAddress ip = IPAddress.Parse(strIPAddress);
            
            byte[] btIPArray       = new byte[6];
            
            uint uiIP = (uint)btIPArray.Length;
            
            int iIPValue = BitConverter.ToInt32(ip.GetAddressBytes(), 0);
            
            int iReturnCode = SendARP(iIPValue, 0, btIPArray, ref uiIP);

            if (iReturnCode != 0)
            {
                return null;
            }

            string[] strIP = new string[(int)uiIP];

            for (int i = 0; i < uiIP; i++)
            {
                strIP[i] = btIPArray[i].ToString("X2");
            }
            string strMacAddress = string.Join(":", strIP);
            return strMacAddress;

        }

    }
}

 

728x90