Skip to content

Instantly share code, notes, and snippets.

@ar45
ar45 / addr.sh
Created February 19, 2017 19:52
Pure shell IPv4 subnet calculations
#!/bin/sh
exit_error()
{
echo "$1" >&2 && exit 1
}
valid_ip()
{
#!/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))"
}
die () {
echo $1
#!/bin/bash
############################
## Methods
############################
prefix_to_bit_netmask() {
prefix=$1;
shift=$(( 32 - prefix ));
bitmask=""
for (( i=0; i < 32; i++ )); do
num=0
cidr2mask() {
local i mask=""
local full_octets=$(($1/8))
local partial_octet=$(($1%8))
for ((i=0;i<4;i+=1)); do
if [ $i -lt $full_octets ]; then
mask+=255
elif [ $i -eq $full_octets ]; then
mask+=$((256 - 2**(8-$partial_octet)))
@mrdima
mrdima / fix-weave-snat.sh
Last active September 24, 2020 09:39
Retain source IP for weave overlay network in Kubernetes
#!/bin/bash
# Inserts or removes iptables rules to prevent snat to the hosts local weave ip ranges
# This way the source ip will be retained for traffic not coming from weave
# Requires weave to be running, the script does wait for weave report to respond
echo running $0 $1
action="${1:-start}"
echo action: ${action}
#functions taken from: https://stackoverflow.com/questions/10768160/ip-address-converter
dec2ip () {
local ip dec=$@
# Strict mode
Set-StrictMode -Version Latest
# Error action
$ErrorActionPreference = "Stop"
# Script's parent path
$PSScriptRoot
# Sets execution policy bypass.
@rsperl
rsperl / convert_between_cidr_and_netmask.sh
Last active July 25, 2022 15:27
convert between cidr and netmask #snippet
#!/bin/bash
# src: https://stackoverflow.com/questions/20762575/explanation-of-convertor-of-cidr-to-netmask-in-linux-shell-netmask2cdir-and-cdir
mask2cidr ()
{
# Assumes there's no "255." after a non-255 byte in the mask
local x=${1##*255.}
set -- 0^^^128^192^224^240^248^252^254^ $(( (${#1} - ${#x})*2 )) ${x%%.*}
x=${1%%$3*}
@ernix
ernix / inet.sh
Last active September 24, 2020 08:00
#/bin/sh
set -eu
ip2dec () {
local ip="$1"
if test -z "$ip"; then
printf "Argument required" 1>&2
return 1
fi
#!/bin/bash
_err() {
printf "$(date +'%Y-%m-%dT%H:%M:%S%z') [ERROR] $@" >&2
}
_usage() {
_err "Usage: $(basename $0) {$(sed "s/ () /|/g; s/ ()$//g;" <<< $(declare -f | egrep "^[[:alpha:]][[:graph:]]+[[:space:]]\(\)"))} \$IPADDR/\$PREFIX\n"
}
@include "lib_netaddr.awk"
function sanitize(ip) {
split(ip, slice, ".")
return slice[1]/1 "." slice[2]/1 "." slice[3]/1 "." slice[4]/1
}
function snbounds(to,i) {
sn_min=grp[1]
sn_max=grp[to]