Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IP Address Converter

Tags:

bash

converter

ip

There is IP address: 66.102.13.19, and from this address as that received this address

http://1113984275

But how? And how I can make this with the help of bash. For example, this service can do it, but I do not understand the algorithm.

like image 902
KarlsD Avatar asked May 26 '12 16:05

KarlsD


1 Answers

ip=66.102.13.19
IFS=. read -r a b c d <<< "$ip"
printf '%s%d\n' "http://" "$((a * 256 ** 3 + b * 256 ** 2 + c * 256 + d))"

By the way, the number in your question doesn't match the IP address.

To convert a decimal to an IP:

#!/bin/bash
dec2ip () {
    local ip dec=$@
    for e in {3..0}
    do
        ((octet = dec / (256 ** e) ))
        ((dec -= octet * 256 ** e))
        ip+=$delim$octet
        delim=.
    done
    printf '%s\n' "$ip"
}

dec2ip "$@"

To convert an IP to a decimal:

#!/bin/bash
ip2dec () {
    local a b c d ip=$@
    IFS=. read -r a b c d <<< "$ip"
    printf '%d\n' "$((a * 256 ** 3 + b * 256 ** 2 + c * 256 + d))"
}

ip2dec "$@"

Demo:

$ ./dec2ip 1113984275
66.102.13.19

$ ./ip2dec 66.102.13.19
1113984275

These two scripts rely on features of Bash that aren't present in some Bourne-derived shells. Here are AWK versions to use instead:

#!/usr/bin/awk -f
# dec2ip
BEGIN {
    dec = ARGV[1]
    for (e = 3; e >= 0; e--) {
        octet = int(dec / (256 ^ e))
        dec -= octet * 256 ^ e
        ip = ip delim octet
        delim = "."
    }
    printf("%s\n", ip)
}

and

#!/usr/bin/awk -f
# ip2dec
BEGIN {
    ip = ARGV[1]
    split(ip, octets, ".")
    for (i = 1; i <= 4; i++) {
        dec += octets[i] * 256 ** (4 - i)
    }
    printf("%i\n", dec)
}

They can be called in the same manner as the Bash scripts above.

like image 186
Dennis Williamson Avatar answered Oct 21 '22 11:10

Dennis Williamson