My Little Corner of the Net

icanhazmyownicanhazip.com

Last night I was playing around with routing in my homelab. I wanted a quick way to verify that traffic was reaching a given machine over a given route, and the easiest way to do that, I figured, was to create an icanhazip.com-esque site to display my client machine’s IP address and verify that it was using one I’d expected. The machine I was connecting to already had a Caddy web server running on it, so it wouldn’t be difficult.

My first thought was to do this with PHP. This would basically be a one-liner:

<?php echo $_SERVER['REMOTE_ADDR']; ?>

The only issue: this machine didn’t have PHP installed, and I wasn’t in the mood to get it set up. Perl or bash script? Caddy doesn’t support old-school CGI without a plugin, and again, I really didn’t want to mess with making a custom Caddy build and setting update-alternatives.

That’s when I remembered that Caddy has support for Go-style templates. In a sort of server-side includes kind of way, Caddy can parse a file before it serves it to do variable substitutions (and more, but that’s a discussion for another time). Surely I’d be able to get the remote IP from the request and inject it in a template, right? Yes…and don’t call me Shirley.

Turns out you don’t even need a template file. You can also do it right in the respond handler. I added this to my Caddyfile, set up the DNS entry in my router, and I was off:

ip.myinternal.domain {
    header Content-Type text/plain
    templates
    respond {{.RemoteIP}} 200
}

You’ll need to reload Caddy to pick up the new config, and be sure to update myinternal.domain with something routable on your network. Then just point your browser at that address and you’ll see your current IP address. It’s not incredibly useful on a local network, but it was fun to figure out.

Leave a Reply

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

<