Mac Address validation algorithm

Asked

Viewed 2,165 times

2

Does anyone know the validation algorithm used by this site?

http://sqa.fyicenter.com/Online_Test_Tools/MAC_Address_Format_Validator.php

I searched a lot on the Internet but I could not find, the site even tells how it is done but I do not have much time to study.. then I wonder if anyone has one ready now..

Note: remembering that it is the validation of Mac Address as existence, not just the format.

Language preference: Javascript or PHP

  • 1

    Neither PHP nor Javascript can access devices remotely to detect MAC addresses, not even the user accessing the page. The only address you could get would be from the equipment connected to the server where PHP is hosted, and this using the command arp combined with functions such as exec() of PHP.

  • @Guilhermenascimento yes.. is that I get a Mac Address and would like to check if it is real

  • 1

    With php you can, with the Mikrotik API, but then you would have to have access to CCR.

  • 2

    It is only possible to validate the format, as said to check if it is real would have to do a remote access and this is not possible and any argument of anyone stating that it is possible will probably be a non-functional solution or extremely limited.

  • 1

    To validate an entry, only the format, has a lot ready and simple, one of them is by regex: http://stackoverflow.com/questions/4260467/what-is-a-regular-expression-fora-mac-address

  • 1

    @Guilhermenascimento believes that for him it is a little difficult, because he would have to have access to MV to check the dialed PPP clients and thus recover their MAC. I believe that this issue is more for the network than programming itself.

  • 2

    There’s no way to verify it’s real. It can only be validated if it is a "known brand", because not all manufacturers respect it (and some pass themselves by others, mainly in the "second line" market). Virtually any 6 bytes described in hexa are valid.

  • @Bacco believes that if he wants to validate only the form of MAC 24:A4:3C:80:EC:80 to see if it is "valid" according to IEEE 802 is possible. But not exact. If you take this MAC that I sent up and test on any site (which does what the questioner wants), it won’t work. This mac is 5.8 (radio) and is valid. However on some websites it will be invalid.

  • @Mauroalexandre I think not, as the AP said: > Note: remembering that it is the validation of Mac Address as existence, not just the format.

Show 4 more comments

2 answers

7


Cannot detect if the address of MAC is real, first you need to understand what is an address of MAC, according to wiki:

The Address MAC (Media Access Control) is a physical address associated with the communication interface, which connects a device to the network. The MAC is a "unique" address, with no two ports having the same numbering, and is used for access control in computer networks. Its identification is recorded in hardware, that is, in the ROM memory of the equipment network card like desktops, notebooks, routers, smartphones, tablets, network printers, etc.

Then understand that:

  • Physical address can only be observed in LAN
  • Will not be public (or propagated to internet)
  • It will be available through mapping by ARP
  • You may be able to make the data public, but this will be from the specific equipment you set up and "forced/made available"

Note that even getting it via a language running on a "lower level" and on LAN it was a little complicated for me (It is possible to determine the hardware address of the router?)

I was forced to use commands like (Windows OS) to get all connected addresses on the same network and "visible":

arp -a

Exit:

Interface: 192.168.2.54 --- 0xe
  Endereço IP           Endereço físico       Tipo
  192.168.2.1           b8-38-61-5d-84-28     dinâmico
  192.168.2.2           48-f8-b3-bc-45-d1     dinâmico
  192.168.2.4           c0-4a-00-87-aa-d6     dinâmico
  192.168.2.150         88-51-fb-22-31-9a     dinâmico
  192.168.2.255         ff-ff-ff-ff-ff-ff     estático
  224.0.0.2             01-00-5e-00-00-02     estático
  224.0.0.252           01-00-5e-00-00-fc     estático
  239.255.255.250       01-00-5e-7f-ff-fa     estático
  255.255.255.255       ff-ff-ff-ff-ff-ff     estático

Then take address from a specified gateway or ip:

arp -a 129.168.0.1

Exit:

Interface: 192.168.2.54 --- 0xe
  Endereço IP           Endereço físico       Tipo
  192.168.2.1           b8-38-61-5d-84-28     dinâmico

Retrieve data with ipconfig:

ipconfig /all

Exit:

Configuração de IP do Windows

   Nome do host. . . . . . . . . . . . . . . . : guilherme-PC
   Sufixo DNS primário . . . . . . . . . . . . :
   Tipo de nó. . . . . . . . . . . . . . . . . : híbrido
   Roteamento de IP ativado. . . . . . . . . . : não
   Proxy WINS ativado. . . . . . . . . . . . . : não
   Lista de pesquisa de sufixo DNS . . . . . . : home

Adaptador de Rede sem Fio Conexão de Rede sem Fio:

   Sufixo DNS específico de conexão. . . . . . : router5d8428.com
   Descrição . . . . . . . . . . . . . . . . . : Intel(R) WiFi Link 1000 BGN
   Endereço Físico . . . . . . . . . . . . . . : 00-26-C7-D8-E8-08
   DHCP Habilitado . . . . . . . . . . . . . . : Sim
   Configuração Automática Habilitada. . . . . : Sim
   Endereço IPv6 de link local . . . . . . . . : fe80::34d0:d738:4aab:83cf%14(Preferencial)
   Endereço IPv4. . . . . . . .  . . . . . . . : 192.168.2.54(Preferencial)
   Máscara de Sub-rede . . . . . . . . . . . . : 255.255.255.0
   Concessão Obtida. . . . . . . . . . . . . . : quinta-feira, 17 de novembro de 2016 15:41:07
   Concessão Expira. . . . . . . . . . . . . . : domingo, 20 de novembro de 2016 03:57:36
   Gateway Padrão. . . . . . . . . . . . . . . : 192.168.2.1
   Servidor DHCP . . . . . . . . . . . . . . . : 192.168.2.1
   IAID de DHCPv6. . . . . . . . . . . . . . . : 184559303
   DUID de Cliente DHCPv6. . . . . . . . . . . : 00-01-00-01-1F-8D-3F-74-3C-4A-92-4E-40-CC
   Servidores DNS. . . . . . . . . . . . . . . : fd37:267c:7d7a:1:204:dfff:fe8c:e72d
                                                 192.168.2.1
   NetBIOS em Tcpip. . . . . . . . . . . . . . : Habilitado
   Lista de pesquisa de sufixos DNS específicos da conexão: home

How is format?

According to the wiki:

The image below presents a simplified version of the framework used in local Ethernet networks, known as Ethernet frame. The first address identifies the recipient of the message, that is, the receiver. The second address identifies the sender, that is, the transmitter. Each address is formed by six bytes, theoretically allowing 2 addresses. For example, the number 00-0C-6E-3C-D1-6D represents an Ethernet address in hexadecimal format.

You can then validate by PHP or Javascript only the format, using a thus:

^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$

An example in PHP would be:

<?php
$mac_address = empty($_GET['mac_address']) ? '' : $_GET['mac_address'];

if (preg_match('#^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$#', $mac_address) > 0) {
     echo 'Validou!';
} else {
     echo 'Não Validou!';
}

If accepting lower case letters (you can simply apply the modifier i, example preg_match('#^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$#i', $mac_address)

Javascript:

function validaEnderecoFisico(endereco) {
    return /^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$/.test(endereco);
}

var input = document.getElementById("mac_address");
var btn   = document.getElementById("validar");

btn.onclick = function() {
    if (validaEnderecoFisico(input.value)) {
        alert("Validou");
    } else {
        alert("Não validou");
        return false;
    }
};
<input placeholder="Digite seu endereço de MAC" type="text" id="mac_address" name="mac_address" size="26">
<button id="validar" type="button">validar</button>

If accepting lower case letters (you can simply apply the modifier i, example /^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$/i.test(endereco)


However

However @Bacco pointed out to me a service that can help do this http://macvendorlookup.com, they have a REST API that can help you check:

For example, sign in (switch to the desired Mac address): http://www.macvendorlookup.com/api/v2/00-23-AB-7B-58-99

Still before using have the consciousness that as the @Bacco said:

There’s no way to verify it’s real. It can only be validated if it is a "known brand", because not all manufacturers respect it (and some pass themselves by others, mainly in the "second line" market). Virtually any 6 bytes described in hexa are valid.

Some may try to pass themselves off as others.

However, a simple example of using the PHP API would be:

<?php 
$enderecoMac = 'DIGITE SEU ENDEREÇO DE MAC';
$url = 'http://www.macvendorlookup.com/api/v2/' . urlencode($enderecoMac);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);

$curl_err = curl_errno($ch);

if ($curl_err != 0) {
    $result = array( 'error' => 'Erro ao usar o CURL: ' . $curl_err );
} else {
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if ($httpCode != 200) {
        $result = array( 'error' => 'Erro ao baixar: ' . $httpCode );
    } else {
        $result = json_decode($data);
        $data = null;
    }
}

curl_close($ch);

var_dump($result);

2

Good, according to the website you put the MAC standard can be:

  • 6 hexadecimal groups separated by hyphene (-), Ex. 01-23-45-67-89-ab

  • 6 groups of 2 hexadecimals separated by two points (:), Ex. 01:23:45:67:89:ab

  • 3 groups of 4 hexadecimals separated by a point (.), Ex. 0123.4567.89ab

In view of this pattern we can make a regex to validate all cases, starting with the first 2 that are practically the same, only changing the separator:

( ([0-9a-fA-F]{2}[:-]){5} ([0-9a-fA-F]{2}) )

Inside the brackets I define valid hexadecimal values, they would be 0 until 9 and A until F (upper and lower), soon after I define the amount I expect from these values that in the case is {2}, then I have to set the separator which can be two points or hyphen [:-], and right after I set the amount of times this will be repeated, which in this case is the total number of groups-1** and then I put the hexadecimal group again, only this time without the separator.

** The reason to put the total of groups (which in case is 6) minus 1 is so that the end is accepted without the separator, for this reason I repeat the set at the end.

Now let’s go to the latest pattern:

( ([0-9a-fA-F]{4}\.){2} ([0-9a-fA-F]{4}) )

The hexadecimal set is exactly the same as the first patterns, only changing the number of repetitions to {4}, and then I define a new separator (which in case is point) and repeat all this by the total number of groups - 1, and add the group again without the separator at the end.

Below is an example of the working script:

document.querySelector('#mac').addEventListener('keyup', function() {
  
  var status = this.value.match(/^((([0-9a-fA-F]{2}[:-]){5}([0-9a-fA-F]{2}))|(([0-9a-fA-F]{4}\.){2}([0-9a-fA-F]{4})))$/);

  document.querySelector('#result').innerHTML = status ? 'Válido' : 'Inválido';
});
<div>
  <label>Digite o MAC:</label>  
  <input type="text" id="mac">
</div>

<div id="result"> </div>

OBS.: ^ is equal to the beginning of the regex, $ is equal to the end of the regex, and the | is equal to the logical OR.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.