How to log your IP Address

Have you you ever thought: "Mhmmm… was that me behind that IP at this certain point in time?"

Bash script

#!/bin/bash

ipcur=$(curl -s ipecho.net/plain)
if ! tail -n 1 ~/.cronjobs/iplog.csv | grep -q "$ipcur"; then
    {
    printf '%s;' "$(date "+%Y-%m-%d;%H:%M")";
    curl -s ipinfo.io | jq -r '.ip + ";"
    + .hostname + ";"
    + .city + ";"
    + .region + ";"
    + .country + ";"
    + .loc + ";"
    + .org + ";"
    + .postal + ";"';
    } >> ~/.cronjobs/iplog.csv
fi

This bash script checks the current external IP address. If the result differs from the previous, last used IP address it appends a new line with the specified log entries to the csv logfile.

The logged values are as follows:

You may ask yourself why there's two services, ipinfo.io and ipecho.net?

Under certain cirumstances, i.e. when on a mobile connection, I've found ipecho to be faster and it's only querying a single IP value compared to the json block of ipinfo, though I'm not sure if that matters.

time curl ipecho.net/plain;echo

0.00s user 0.00s system 0% cpu 2.317s total


❯ time curl -s ipinfo.io/104.161.79.83
{
  "ip": "104.161.79.83",
  "hostname": "No Hostname",
  "city": "Phoenix",
  "region": "Arizona",
  "country": "US",
  "loc": "33.4319,-112.0150",
  "org": "AS53755 Input Output Flood LLC",
  "postal": "85034"
}

0.00s user 0.01s system 0% cpu 2.572s total

Are you jealeous of my latency? Probably not.

The Logfile

DATETIMEIPHOSTNAMECITYREGIONCCGPSORGANISATIONZIP
2017-01-0100:00104.161.79.83phoenix.crstin.comPhoenixArizonaUS33.4319,-112.0150AS53755 Input Output Flood LLC85034
2017-01-0208:458.8.8.8google-public-dns-a.google.comMountain ViewCaliforniaUS37.3860,-122.0838AS15169 Google Inc.9403
2017-01-0319:3067.215.92.218No HostnameMoragaCaliforniaUS37.8381,-122.1026AS36692 OpenDNS, LLC9455
2017-01-0319:30179.60.192.36edge-star-mini-shv-01-cdg2.facebook.comMenlo ParkCaliforniaUS37.4590,-122.1781AS32934 Facebook, Inc.9402
2017-01-0319:3017.172.224.47velocityengine.comCupertinoCaliforniaUS37.3230,-122.0322AS714 Apple Inc.9501
2017-01-0319:30213.186.33.5redirect.ovh.net  FR48.8582,2.3387AS16276 OVH SA 

CSV Headers

Put this on the first line of iplog.csv to enable csv headers.

DATE;TIME;IP;HOSTNAME;CITY;REGION;COUNTRY;LOCATION;ORG;POSTAL;

Automate the script

Open crontab on the command line and add the cronjob.

❯ crontab -e
# ┌───────────── minute (0 - 59)
# │ ┌───────────── hour (0 - 23)
# │ │ ┌───────────── day of month (1 - 31)
# │ │ │ ┌───────────── month (1 - 12)
# │ │ │ │ ┌───────────── day of week (0 - 6) (Sunday to Saturday;
# │ │ │ │ │                                       7 is also Sunday)
# │ │ │ │ │
# │ │ │ │ │
# * * * * *  command to execute

*/15 *  *  *  *  source ~/.cronjobs/iplog.sh

In this case iplog.sh will be executed every 15 minutes.

System Setup and Services Used: