Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl bitwise AND giving me funky results

I am writing a little perl script to compare two IP addresses using perls bitwise AND operator. but I am getting some really funky results. I'm new to perl so maybe someone can give me a few pointers.

Heres my little script:

#!/usr/bin/perl

$address = "172.34.12.0";
$address2 = "255.255.255.0";

@octets = split (/\./,$address);
@octets2 = split (/\./,$address2);

#Funky results when doing a bitwise AND
#This outputs "050 24 00 0" What's going on here?
print $octets[0] & $octets2[0], "\n";
print $octets[1] & $octets2[1], "\n";
print $octets[2] & $octets2[2], "\n";
print $octets[3] & $octets2[3], "\n";

#Results are what I want when doing it as literals
#This outputs "172 34 12 0"
print 172 & 255, "\n";
print 34 & 255, "\n";
print 12 & 255, "\n";
print 0 & 0, "\n";

Anyone know why or how I got "050 24 00 0" when doing the bitwise AND on the $octets and $octets2 members? Everything seems to work just fine when I do the bitwise AND using literals. Please help. Thanks!

like image 782
Sam Avatar asked Sep 19 '11 23:09

Sam


2 Answers

The bitwise ops act different on strings and numbers, and split returns strings. Convert the strings to numbers using 0+ or int. http://codepad.org/sqHntIgZ:

#!/usr/bin/perl

$address = "172.34.12.0";
$address2 = "255.255.255.0";

@octets = split (/\./,$address);
@octets2 = split (/\./,$address2);

#Funky results when doing a bitwise AND
#This outputs "050 24 00 0" What's going on here?
print int($octets[0]) & int($octets2[0]), "\n";
print int($octets[1]) & int($octets2[1]), "\n";
print int($octets[2]) & int($octets2[2]), "\n";
print int($octets[3]) & int($octets2[3]), "\n";

#Results are what I want when doing it as literals
#This outputs "172 34 12 0"
print 172 & 255, "\n";
print 34 & 255, "\n";
print 12 & 255, "\n";
print 0 & 0, "\n";
like image 137
Jacob Eggers Avatar answered Sep 22 '22 19:09

Jacob Eggers


I suggest that you use a CPAN module such as Net::IP.

Also always put use strict; use warnings; at the top of your program.

like image 24
Bill Ruppert Avatar answered Sep 25 '22 19:09

Bill Ruppert