#!/usr/bin/perl
#
# oui.pl - lookup IEEE OUI info from live data
#
# vom@cinci2600.com - if you make this script better or fix something - drop me a line
#
######################################################################################

use LWP::UserAgent;

if (!$ARGV[0]) { print "Usage: $0 <mac-address>\n"; exit 1; }

$mac = $ARGV[0];

$res = parse($mac);

if ($res =~ "INVALID") { print "Invalid MAC format !\n"; exit 1; }

@details = ieee_lookup($res);

print @details;

exit 0;

sub ieee_lookup
{
	$oui = @_[0];
	my $ua = new LWP::UserAgent;
	$ua->env_proxy;
	my $response = $ua->post('http://standards.ieee.org/cgi-bin/ouisearch',
	{
		x => $oui
	});

	my $content = $response->content; 

	@raw = (split /\n/,$content);

	# process raw html from ieee.org
	foreach $line (@raw)
	{
		if ($line =~ /Sorry\!/) { return "NOT FOUND\n"; }
		if ($line =~ /^.*\(base 16\)/) { $record = 1;}
		if ($line =~ /^<\/pre/) { $record = 0; }
		if ($record == "1")
		{
			# first line, want to start with company name
			$line =~ s/^.*\(base 16\)\s+//;
			# leading whitespeace
			$line =~ s/^\s+//;
			push @output, "$line\n";
		}
	}

	return @output;

}

sub parse
{
	$mac = @_[0];
	PARSE:
	{
		# *nix, etc
		# 00:01:02:03:04:05
		if ($mac =~ /^(([0-9a-fA-F]{2}):){5}[0-9a-fA-F]{2}$/)
		{
			@bytes = split (/:/,$mac); last PARSE;
		}
	
		# Cisco CatOS
		# 00-01-02-03-04-05
		if ($mac =~ /^(([0-9a-fA-F]{2})-){5}[0-9a-fA-F]{2}$/)
		{
			@bytes = split (/-/,$mac); last PARSE;
		}
	
		# Cisco IOS
		# 0001.0203.0405
		if ($mac =~ /^(([0-9a-fA-F]{4})\.){2}[0-9a-fA-F]{4}$/)
		{
			$mac =~ s/\.//g;
			@bytes = unpack ('A2 A2 A2 A2 A2 A2', $mac); last PARSE;
		}
	
		# Raw
		# 000102030405
        	if ($mac =~ /^[0-9a-fA-F]{12}$/)
        	{
                	@bytes = unpack ('A2 A2 A2 A2 A2 A2', $mac); last PARSE;
        	}


	# invalid format
	if (!@bytes) { return "INVALID"; }
	
	}
	
	$oui = $bytes[0]."-".$bytes[1]."-".$bytes[2];
	$oui = lc($oui);

	return $oui;

}


