Philipp
Philipp

Reputation: 4799

Linux shell: write IP to binary file

Using ash, I have an IP address as a variable

IP_ADDR=192.168.1.234

I want to write the 4 bytes to a binary file and later reread them and reform the IP string.

I have the following working solution, but it seems very hacky - any better proposals?

Write:

 IP_ADDR=192.168.1.234
 serialHex=`printf '%02X' ${IP_ADDR//./ } | sed s/'\(..\)'/'\\\\x\1'/g`
 echo -n -e $serialHex | dd bs=1 of=/path/to/file seek=19 &> /dev/null

Note seek=19 indicates where in the binary file (at byte 19) to write

Read:

hexValues=`od -j 19 --read-bytes=4 --address-radix=n -t x1 /path/to/file` 
set $hexValues
for w; do echo -n "$((0x$w))."; done | sed s/.$//

Upvotes: 2

Views: 417

Answers (1)

konsolebox
konsolebox

Reputation: 75568

function ip_write {
    local FILE=$1 IP=$2 NUMS T
    IFS=. read -a NUMS <<< "$IP" 
    printf -v T '\\x%x\\x%x\\x%x\\x%x' "${NUMS[@]}"
    printf "$T" > "$FILE"
}

function ip_read {
    local FILE=$1 NUMS
    read -a NUMS < <(exec od -N4 -An -tu1 "$FILE")
    local IFS=.
    IP="${NUMS[*]}"
}

Example usage:

# Saves IP to file:
> ip_write ip.txt 10.0.0.1
> hexdump -C ip.txt
00000000  0a 00 00 01                                       |....|

# Reads IP from file:
> ip_read ip.txt
> echo "$IP"
10.0.0.1

Upvotes: 1

Related Questions