Saturday, October 24, 2020

From IP to Hex and back again

 Did a one-liner to convert an IP address as a string into a string with 4 hex number pairs.

hexip=$(echo $ip | awk -F '.' '{printf "%02x%02x%02x%02x\n", $1,$2,$3,$4}')

Then from this string back to an IP address.

echo $hexip | grep -Eo '[A-Za-z0-9]{2}' | paste -s | awk -F '\t' '{printf "%d.%d.%d.%d","0x"$1,"0x"$2,"0x"$3,"0x"$4}'

Edit: It has occurred to me that given the fixed nature of the hexip string (it is always character pairs) there is no reason to grep and paste before using awk. Instead, this can all be done with one awk program.

echo $hexip | awk -F " " '{gsub(/../,"& "); printf "%d.%d.%d.%d","0x"$1,"0x"$2,"0x"$3,"0x"$4}'

IP and Grep to extract address

 This is just another one line command to extract a system IP address

ip -4 a show eth0 | grep -oP '(?<=inet\s)\d+(\.\d+){3}'

IP and JQ to extract address

 So I wanted to try to extract just the IP address of a named network adapter using bash. There are lots of ways to do this, but it turns out that the linux ip command supports output to JSON. This gets me thinking jq. After testing on Manjaro and Amazon Linux 2, this is the most reliable command I found.

ip -4 -j a | jq -r '.[] | select(.ifname | contains("eth0")) | .addr_info[].local'

Obviously the interface name is going to be different on different systems

 RasPi Pico and an OLED Screen My project for this morning was to connect a small I2C OLED screen to Raspberry Pi Pico and make it do someth...