Hi Kipp,

I'd say don't bother pack()ing.  At the moment, I think the function pretty much 
s**ks.  use eval() instead.  The following doesn't have that one-liner compactness of 
the others, but it shows you what is going on.  The bitwise & does a real cute little 
trick with its operands, evaluating them in hex context or digit-by-digit (I can't 
tell which, and the two may be functionally indistinguishable.)  Therefore I got 
results like 192 & 255 = 010 [the nine and five match on the 0 bit, no other digits 
match any bits with their corresponding digit in the other number.

That doesn't quite get us there.  Here is my approach:

#!/usr/bin/perl

my ($IP_String, $MaskString) = split(/ +/, $ARGV[0]);
@IP_Address = ExtractBytes($IP_String);
@Mask = ExtractBytes($MaskString);
@NetworkAddress = AND_MaskArray(4, \@IP_Address, \@Mask, $ARGV);
print
"$NetworkAddress[0]\.$NetworkAddress[1]\.$NetworkAddress[2]\.$NetworkAddress[3]";

sub ExtractBytes {
  my $DottedString = $_[0];
  @AddressBytes = split (/\./, $DottedString);
  return @AddressBytes;
}

sub AND_MaskArray {
  $limit = $_[0];
  my @result;
  for (my $i = 0; $i < $limit; $i++) {
    $Temp = eval($IP_Address[$i]) & eval($Mask[$i]);
    $result[$i] = $Temp;
  }
  return @result;
}

And will handle any kind of and-masking.  I had it set up to do or-ing, too, then 
dumped that part when I could concieve of no useful purpose for or-ing IPs.  This will 
also extract a classless IP subnet, or a host mask if the parameters are reversed.

E:\d_drive\perlStuff>andips.pl "192.168.0.102 255.255.0.0"
192.168.0.0
E:\d_drive\perlStuff>andips.pl "221.215.156.68 255.255.255.128"
221.215.156.0
E:\d_drive\perlStuff>andips.pl "221.215.156.168 255.255.255.128"
221.215.156.128
E:\d_drive\perlStuff>andips.pl "221.215.156.168 0.0.0.127"

Joseph

"Kipp, James" wrote:

> Happy Hollidays
>
> I want to bitwize AND 2 IP adr strings, not sure of how to pack() them to be
> able to AND them. before i start playing with pack,sprintf,socket,etc.. I
> was wondering if someone already had a way.
>
> Thanks
>
>
>
> --
> To unsubscribe, e-mail: [EMAIL PROTECTED]
> For additional commands, e-mail: [EMAIL PROTECTED]


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to