Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Verify string as ethernet address

by fs (Monk)
on May 30, 2001 at 03:03 UTC ( [id://84130]=CUFP: print w/replies, xml ) Need Help??

While writing a web page that allows users to register new hosts for the campus LAN. Among other bits of info that has to be entered is the ethernet address - something which quite a few users try to enter bogus data in, or at least enter it in one of the many different formats used. This bit of code takes in an ethernet address in all of the formats I've come across so far, and returns the "normalized" version (all caps, 2 char octets, colon seperated) or undef if it's not a valid ethernet address.
sub verify_ether($){ my $mac = uc(shift); $mac =~ s/-/:/g; my @octets; if($mac =~ /^[0-9A-F]{12}$/){ $mac = join(':', unpack("A2" x 6, $mac)); }elsif ($mac =~ /^(([0-9A-F]{1,2}?):){5}([0-9A-F]{1,2})$/ ){ @octets = split(/:/, $mac); map { if (length($_)==1) { $_ = "0" . $_ } } @octets; $mac = join(':', @octets); }else{ return undef; } return $mac; }

Replies are listed 'Best First'.
Re: Verify string as ethernet address
by petdance (Parson) on May 30, 2001 at 06:33 UTC
    This was just discussed a few days ago. You may find tidbits & comments over there.

    xoxo,
    Andy

    %_=split/;/,".;;n;u;e;ot;t;her;c; ".   #   Andy Lester
    'Perl ;@; a;a;j;m;er;y;t;p;n;d;s;o;'.  #   http://petdance.com
    "hack";print map delete$_{$_},split//,q<   andy@petdance.com   >
    
Re: Verify string as ethernet address
by suaveant (Parson) on May 30, 2001 at 20:59 UTC
    I would probably change
    $mac =~ s/-/:/g; #to $mac =~ s/[^0-9A-F]+/:/g;
    weed out all the trash chars, I mean, why not?
                    - Ant
      ":" and "-" are equivalent octet seperators. The presence of any other characters means the string isn't a valid ethernet address. With that change "dead beef is cool!" would match, but it shouldn't.
        Macintoshes tend to display their MAC address as a series of space separated octets. What you really want to do is to check that the octets are separated by a \W character. That way, you'll get "44:45 53,4f'2g;56" but not "dead beef is cool!". -- iain. <http://eh.org/~koschei/>
        oooh, you're assuming users are typing in separators they are supposed to, or failing... that works too... :)
                        - Ant

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: CUFP [id://84130]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (5)
As of 2024-04-16 22:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found