We have a Java web service that gets a String representing a MAC address. We want to validate if the given String actually matches the required format. Further we want to create a normalized form to make them comparable.

I searched quite a while but found only some "loose regular expressions". We would really prefer to have a library that can parse different formats and return a normalized (String) representation (i.e. 01-23-45-67-89-ab and 01:23:45:67:89:ab would return the same representation and be comparable).

I expected to find some mature and well tested library, which could do that kind of task. Can anyone please point me to it? I just cannot believe that it doesn't exist yet.

I would be very thankful to not see any RegExes as possible solutions (we know how to do that if necessary).

有帮助吗?

解决方案

The IPAddress Java library will do it. The javadoc is available at the link. Disclaimer: I am the project manager.

The library will read various common formats for MAC addresses, like aa:bb:cc:dd:ee:ff, aa-bb-cc-dd-ee-ff, aabb.ccdd.eeff, it supports addresses that are 48 or 64 bits, and also allows you to specify ranges of addresses like aa-ff:bb:cc:*:ee:ff

Verify if an address is valid:

    String str = "aa:bb:cc:dd:ee:ff";
    MACAddressString addrString = new MACAddressString(str);
    try {
         MACAddress addr = addrString.toAddress();
         ...
    } catch(AddressStringException e) {
        //e.getMessage provides validation issue
    }

The library is well tested, it has a test suite with thousands of tests.

其他提示

mature and well tested library

To verify MAC addresses? It's 6 bytes in hex optionally separated by a delimiter. It's a homework assignment or light interview question, no need to write a library. My solution is 10 lines, and it's more paranoid than necessary...

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top