Easily map an IP to its BGP Announced Prefix

Suppose I'm connecting from home to a server over SSH.
That server is about to change default gateways (perhaps connecting over a vpn). I need to make sure I'm not thrown off, either now or in the future, and I have a dynamic IP.

The server needs to find what my home network is announced as to the internet and create a static route.

Team-Cymru provides a DNS lookup service for mapping IP addresses to ASNs and their announced prefixes.

It's pretty simple,
For IP address, you can retrieve the record as TXT record at

  $ dig +short TXT
  "15169 | | US | arin | 1992-12-01"

Bash function

  lookup_bgp_route() {
    host -t txt $(awk -F. '{print $4"."$3"."$2"."$1}'<<<$1).origin.asn.cymru.com 
    | cut -d\" -f2 | awk -F " | " '{print $3}'


Finding the SSH client prefix

 sshroute=`lookup_bgp_route ${SSH_CLIENT%% *}`    

The %% * operator truncates the variable after the first space (we only need the first word)

Adding a static route

the prefix of the current SSH client will always go through the current default root

  ip r add $sshroute $(ip r list | sed s/default\ //)

Then we add new route default route or whatever

The steps used to process the output (for practice)

1. First, reverse the ip address and convert it into the reverse DNS format using awk

  dnsrecord=$(awk -F. '{print $4"."$3"."$2"."$1}'<<<$ip).origin.asn.cymru.com 

  host -t txt $dnsrecord descriptive text "15169 | | US | arin | 1992-12-01"

2. Then, snip the quotes, getting the inner text (removing the additional output from host)

  host -t txt $dnsrecord | cut -d\" -f2 
  15169 | | US | arin | 1992-12-01

3. Lastly, we delimit using " | "

  host -t txt $dnsrecord | cut -d\" -f2 | awk -F " | " '{print $3}'