Three ways to get your MAC address

Source: Internet
Author: User
Tags get ip
Three ways to get your MAC address


Environment: compiled on: Visual Studio. NET & Windows XP Pro. Tested on Win2k Server & WINXP pro

I recently wrote two articles referenced below on how to get your IP address in C ++ and C # respectively. I found that people commented wondering how to get their MAC address, so I decided that it might be wise to follow up with an in depth discussion of the issue at hand.

OSI 7 Layer Model
As you may know there are 7 layers in the OSI (Open Systems Interconnection) model. Specifically one can describe them as below.

Layer 7: Application Layer
Layer 6: Presentation Layer
Layer 5: Session Layer
Layer 4: Transport Layer
Layer 3: Network Layer
Layer 2: Data Link Layer
Layer 1: Physical Layer
Now we can interpret the physical layer as the point at which the wires are connecting the network together. it is the physical, raw cabling and the ones and zeros going over the analog wiring at a given rate. one can have the Internet running on your different types of networks, and the cabling at the end comes down to a pair of wires or more depending on the standard being used (eg. ethernet, IBM Token Ring, PPP ...). the physical layer encompasses the electrical signals and cabling issues.
The data link layer is responsible for transfering discreet packets of information over the physical layer. This layer must be error free and does not deal with routing issues.

It can be described as the method in which two PCs communicate over the physical network layer. let us take the Ethernet cards for example. apart from every computer on the Internet having an IP address, each Ethernet computer has a 48-bit MAC address. this is the media access control layer and along with the LLC (logic link layer) compose the entire data link layer in an Ethernet example. the Mac is the layer that deals with full duplex or half duplex Ethernet cards, 10/100 or Gigabit Ethernet speed transfers; it also the one dealing with Point to Point addressing. mac can have several types of packets running on top of it including IP, IPX, appletalk, ATM, X. 25 and LAN Manager. LLC deals with frame synchronization, flow control and error checking.

The network layer is essential handled by the IP layer in a TCP/IP stack. IPX/SPX wocould be handling the network layer and Transport Layer in an Novell IPX world. the network layer deals with routing issues, forwarding issues and making sure that the packets are within the maximum packet size (MTU) and fragmenting them if not. it also deals with recycling them at the point of entry. the network layer also has the essence of IP which is IPv4 addressing. the network layer also deals with things such as ICMP, ARP and RARP as well as the issues mentioned above.

The last layer that is encompassed by TCP/IP is the transport layer. by far the most widely used Mac type used is IP, where TCP and UDP are derived from; the standard IPv4 dotted notation 32-bit IP address. the transport layer corresponds to the TCP of TCP/IP; TCP stands for transmission control protocol and UDP for user datemediprotocol. one can also consider UDP as an alternate method of transport, although it is connectionless and does not handle errorless transfers (Can Drop packets ). the transport layer is responsible for end to end communication and errorless transfer of data including flow control, TCP is the primary handler of this task and performs it well. the TCP/IP stack needs to deal with an extra level of packet sequencing because of the given wing protocol, along with flow control issues and retransmission of lost packets.

Finally the session, presentation and application layer have not yet been solidified in any real manner (eg. like the other layers have been with TCP/IP, Ethernet, etc ). people seem to consider protocols such as FTP, SMTP, telnet, POP3 and such as being on the application layer or in a composition of all three layers. on top of that, it is the programmer's prerogative of layering the software in a modular approach.

Why do I want a MAC address?
When computers talk over TCP/IP or UDP/IP the computers whom wish to speak to the destination IP computer ARP for the destination computer's MAC address. the TCP/IP implementations require the IP to Mac translation and in reverse (RARP ). this is the only way data gets transferred over the Internet, by going through the layers from Layer 7 to layer 1 and back. hence when you send a packet to an IP address, the network layer finds the destination MAC and sends the packets to that MAC address. in a LAN setting, you usually hit the destination ethernet card yourself through maybe some switches or hubs. in an Internet setting, you go through varous routers which do some analysis of TCP/IP headers and it finally arrives at the destination ethernet card. you must realize that every ethernet card in the world has a unique MAC address.

When you are a Winsock programmer dealing exclusively with sockets, I doubt you wowould care what the MAC addresses of the related blocks (network interface card) are because you wowould never need to know about them. this is a low level issue which one needs not be exposed to in a network programming environment.

There are specific reasons why you may need to know the MAC address. personally I had to write the media access control layer in an HDL language at one point. I had hard coded the FPGA to a certain Mac and created a static ARP so that I cocould write sockets software on my PC which wocould send UDP packets to my Mac. the Mac wocould then decipher and verify the checksum, and CRC of the UDP and Mac packets. it wowould then take the payload and forward it along to an RS232 interface. the rsr232 interface was connected to a bluetooth device via RFCOMM. your reason for knowing a MAC address may be different.

We will deal with enumerating the MAC address of all the records in your computer in a Windows environment.

Deciphering the 48-bit MAC address
The 48-bit MAC address is a globally unique identifier. each ethernet card in the world has a unique MAC address. the first 24 bits correspond to the organizationally unique identifier. the second 24 bits is administered by the company or organization that the Oui has been assigned. you will notice that All 3Com cards, for example, will have the same oui, the first 3 ETS in a MAC address.

How do I get a MAC address via command line?
Okay, there are several command line utilities to get your MAC address. the first one that comes to mind is getmac. simply open a command prompt and type getmac and it will return your 48-bit MAC address in the following format:

Physical address transport name
========================================================== ====================================
00-40-ca-b5-5b-06/device/TCPIP _ {B249BB63-9574-4061-817A-D62E1D12072F}

The next method of doing it is writing ipconfig/all, this will also get all the MAC addresses of your Ethernet cards along with all the IP addresses setup for each Ethernet card. information such as your gateway, WINS server, DNS server, subnet mask, and all the IPS associated with your each Nic.
An interesting way to discover what MAC addresses you know of other people on your network is to type ARP-a in a command prompt and you shoshould get a listing that is similar to this.

Interface: --- 0x2
Internet address physical address type 00-20-78-d9-5c-b3 dynamic 00-50-ba-b3-55-ec dynamic 00-a0-cc-7a-7d-6d dynamic

How do I get a Mac in C or C ++, Win32 environment?
There are numerous ways to do this. as I was on my investigation, I realized that there was no clear and simple way to do this. A lot of people said to use netstat and to parse the result. some people said to create a uuid and pull the Mac from there. A couple of people said to use netbios, and finally one said to query the NDIS miniport driver itself.

Although the last solution sounded the coolest, apparently doing that from user mode wasn' t the easiest thing to do. i'll give you a set of solutions from worst to best and then a quick Discussion of The miniport method.

Method One: uuidcreate
One quick way to find out your MAC address, which is very hacky and I wouldn't recommend wocould be to create a sequential UUID. apparently Microsoft uses your MAC address to help it create a universally unique identifier.

All you have to do is check out bytes 2 through 8 and you are done. The code is below and the downloadable EXE and sample code is listed at the end of the article.

Code:// Fetches the MAC address and prints it
Static void getmacaddress (void)
Unsigned char macdata [6];

Uuidcreatesequential (& UUID); // ask OS to create UUID

For (INT I = 2; I <8; I ++) // bytes 2 through 7 random sive
// Are MAC address
Macdata [I-2] = UUID. data4 [I];

Printmacaddress (macdata); // print MAC address
} [Copy to clipboard]

This code will only work in Windows 2000/XP since Microsoft replaced uuuidcreate in Windows 2000/XP with one that doesn't use the PC's MAC address. uuidcreate with your MAC address can easily be considered a security risk since you are distributing your Ethernet Card's address.
Microsoft created uuidcreatesequential in Win2k and XP to do what the old uuidcreate did on Windows 95/98/ME. the current uuidcreate in Windows 2000/XP is not composed of a number which provided des the MAC address of your primary Nic, hence they moved over that functionality to uuidcreatesequential. on the older OSes you may still use the uuidcreate function to obtain its MAC address.

This example only supports one Nic card on your PC.

METHOD Two: use netbios
This solution is a lot more complicated then the final solution. it supports multiple Nic cards, but requires NetBIOS to be installed on the computer. it also requires you to have the cable connected to a valid NetBIOS network. it works great under all OSes including 95/98/ME/NT/2000/XP.

Code:// Fetches the MAC address and prints it
Static void getmacaddress (void)
Unsigned char macdata [8]; // allocate Data Structure
// For MAC (6 bytes needed)

Wksta_transport_info_0 * pwkti; // allocate Data Structure
// For Netbios
DWORD dwentriesread;
DWORD dwtotalentries;
Byte * pbbuffer;

// Get MAC address via NetBIOS's enumerate Function
Net_api_status dwstatus = netwkstatransportenum (
Null, // [in] server name
0, // [in] Data Structure to return
& Pbbuffer, // [out] pointer to buffer
Max_preferred_length, // [in] maximum length
& Dwentriesread, // [out] counter of Elements
// Actually enumerated
& Dwtotalentries, // [out] Total number of elements
// That cocould be enumerated
Null); // [in/out] resume handle
Assert (dwstatus = nerr_success );

Pwkti = (wksta_transport_info_0 *) pbbuffer; // type cast the buffer

For (DWORD I = 1; I <dwentriesread; I ++) // first address is
// 00000000, skip it
{// Enumerate Macs & print
Swscanf (wchar_t *) pwkti [I]. wkti0_transport_address,
L "% 2hx % 2hx % 2hx % 2hx % 2hx % 2hx % 2hx ",
& Macdata [0],
& Macdata [1],
& Macdata [2],
& Macdata [3],
& Macdata [4],
& Macdata [5]);
Printmacaddress (macdata );

// Release pbbuffer allocated by above function
Dwstatus = netapibufferfree (pbbuffer );
Assert (dwstatus = nerr_success );
} [Copy to clipboard]

As you can tell converting the wide string which is returned from netwkstatransportenum to an byte based array is a mess in itself. the great thing about this is that it goes through all the other located on your PC. you are also able to easily query other people's PCs by passing in a NetBIOS computer name as the first parameter to this function.

Method three: Use getadaptersinfo
The cleanest way I cocould find to get all the MAC addresses located on a PC was to use the getadaptersinfo method. IT administrators des almost as much information as ipconfig/all including your DHCP server, gateway, IP address list, subnet mask and WINS servers. it also enumerates all the records on your PC and is supported in 95/98/ME/NT/2000/XP. finally it also works if your networks are not connected to valid networks (eg. wires are not even hooked up), but the specified do have to be "enabled" in windows.

Code:// Fetches the MAC address and prints it
Static void getmacaddress (void)
Ip_adapter_info adapterinfo [16]; // allocate Information
// For up to 16 seconds
DWORD dwbuflen = sizeof (adapterinfo); // save memory size of Buffer

DWORD dwstatus = getadaptersinfo (// call getadapterinfo
Adapterinfo, // [out] buffer to receive data
& Dwbuflen); // [in] size of receive data buffer
Assert (dwstatus = error_success); // verify return value is
// Valid, no Buffer Overflow

Pip_adapter_info padapterinfo = adapterinfo; // contains pointer
// Current adapter info
Do {
Printmacaddress (padapterinfo-> address); // print MAC address
Padapterinfo = padapterinfo-> next; // progress through
// Linked list
While (padapterinfo); // terminate if last Adapter
} [Copy to clipboard]

I probably shocould mention that statically allocating an array for up to 16 rows is not the best way to do this. it is a quick and dirty solution that shocould show you how to get and enumerate all the MAC addresses on your PC.

Method four: The miniport driver
I never implemented this method since it required some very low level coding. it also probably wouldn't be a good method since you are directly talking to the underlying NDIS miniport driver. the basic concept of this is to hit the miniport driver with an OIS query of oid_802_3_current_address. this shoshould return a buffer with the current MAC address.

The way problem with this solution is that there is no easy way to do this from user mode, which is exactly the mode we are coding all our apps in, this is as opposed to kernal mode which drivers reside in.

Although there are no functions named getmacaddress In the Win32 API, ATL, MFC, or C #, it is fairly easy to find and associate your MAC address with its related IP addresses by calling getadaptersinfo (). getadaptersinfo is located in the Platform SDK.

I hope you had an interesting time reading this article.

Reference: Get IP address in C #
Reference: Get IP address in C ++

About the author
Khalid Shaikh is a software engineer currently contracting for HP in Palo Alto. he has worked at such companies such as Microsoft, NVIDIA, and several Silicon Valley startups. khalid has been featured in PC gamer for innovative driver development techniques and is currently co-founder of HTTP-tunnel Corp.



Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.