]> Tony Duckles's Git Repositories (git.nynim.org) - dotfiles.git/blob - bin/ipaddr
.bashrc: Use GNU awk on Solaris
[dotfiles.git] / bin / ipaddr
1 #!/bin/sh
2 # Usage: ipaddr [<iface>]
3 # Show the IP address (IPv4 and/or IPv6) for interface <iface> or all interfaces
4 # when no <iface> given.
5
6 UNAME=$(uname)
7 IFACE=$1
8 awk="command awk"
9
10 # Helper function for converting a hex (or decimal) netmask into CIDR format
11 awk_mask2cdr='
12 function mask2cdr(mask) {
13 if(mask ~ /[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/) {
14 split(mask,d,".");
15 mask = sprintf("0x%x%x%x%x",d[1],d[2],d[3],d[4]);
16 };
17 sub("^0x","",mask);
18 cidr=0;
19 while(mask != "") {
20 digit=substr(mask,1,1);
21 mask=substr(mask,2);
22 if(digit ~ /f|F/) cidr += 4;
23 if(digit ~ /e|E/) cidr += 3;
24 if(digit ~ /c|C/) cidr += 2;
25 if(digit ~ /8/) cidr += 1;
26 };
27 return cidr
28 };'
29
30 case "$UNAME" in
31 Darwin|FreeBSD)
32 test -n "$IFACE" && if_args="$IFACE"
33 test -z "$if_args" && if_args="-a"
34 ifconfig $if_args | $awk "$awk_mask2cdr"'
35 /^[a-z-0-9]/ {iface=$1};
36 $1 == "inet" {printf("%-10s %s/%s\n",iface,$2,mask2cdr($4))};
37 $1 == "inet6" && !/scopeid|inet6 ::1|temporary/ {printf("%-10s %s/%s\n",iface,$2,$4)}'
38 ;;
39 Linux)
40 test -n "$IFACE" && if_args="$IFACE"
41 test -z "$if_args" && if_args="-a"
42 ifconfig $if_args | $awk "$awk_mask2cdr"'
43 /^[^ ]+/ {iface=$1};
44 $1 == "inet" { printf("%-10s %s/%s\n", iface ":", substr($2,6), mask2cdr(substr($0,index($0,"Mask:")+5))) };
45 $1 == "inet6" && /Scope:Global/ { printf("%-10s%s\n", iface ":", $3) }'
46 ;;
47 SunOS)
48 test -x "/usr/gnu/bin/awk" && awk=/usr/gnu/bin/awk
49 test -n "$IFACE" && if_args="$IFACE"
50 test -z "$if_args" && if_args="-a"
51 ifconfig $if_args | $awk "$awk_mask2cdr"'
52 /^[a-z0-9]+/ {iface=$1};
53 $1 == "inet" { printf("%-10s %s/%s\n", iface, $2, mask2cdr($4)) };
54 $1 == "inet6" && !/inet6 ::|inet6 fe80:/ { printf("%-10s %s\n", iface, $2) }'
55 ;;
56 *)
57 echo "Unhandled host-type: $UNAME"
58 esac