Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

IP Address ASCII to Decimal

Status
Not open for further replies.

dakota81

Technical User
May 15, 2001
1,691
US
I'm rather unfamiliar with Perl, want to know if there is built in functions to convert dotted decimal notation ip addresses to a number, and back again.
 
Do you mean convert 192.100.43.52 to 1921004352 and back to 192.100.43.52?

[blue]"Well, once again my friend, we find that science is a two headed beast. One head is nice, it gives us aspirin and other modern conveniences,...but the other head of science is BAD! Oh, beware the other head of science, Arthur; it bites!!" - The Tick[/blue]
 
I mean convert 192.100.43.52 to 3227790132 and back to 192.100.43.52.
 
Not that I'm aware of, but I am aware that there is a lot that I'm not aware of. :)

[blue]"Well, once again my friend, we find that science is a two headed beast. One head is nice, it gives us aspirin and other modern conveniences,...but the other head of science is BAD! Oh, beware the other head of science, Arthur; it bites!!" - The Tick[/blue]
 
I know how to do it the long way if needs be, just asking first. I just want to put ip addresses into a database field and want them in decimal notation.
 
Code:
# forward
$ip = "192.100.43.52";
@fields = split(/\./, $ip);
$sum = 0;
foreach $field (@fields) {
    $sum *= 256;
    $sum += $field;
}
print "$sum\n";

# reverse
@fields = ();
while ($sum > 256) {
    $rem = $sum%256;
    $sum = int($sum/256);
    unshift @fields, $rem;
}
unshift @fields, $sum;
$" = ".";
print "@fields\n";
Cheers, Neil
 
Or another way, using the Socket module:
Code:
use Socket;
$ip = "192.100.43.52";

# forward
$n = inet_aton($ip);
$dec = unpack("I", $n);
print "$dec\n";

# reverse
$n = pack("I", $dec);
$ip = inet_ntoa($n);
print "$ip\n";
Cheers, Neil
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top