Access your localhost even if your IP changes

Have you ever wanted to access your localhost from outside your local network but found it difficult because your ISP set you up with a dynamic IP? I have. my Couchpotato setup was working nice and swiftly on my local machine, but trying to access it from outside my local network was frustrating. Sure, I could check my public IP, write it down somewhere and everything would be fine… until it didn’t work.

Like most people, I have a dynamic IP. This is annoying because there’s no reliable way to access your computer from outside the local network if you don’t have an static IP. Unfortunately, there’s no way to fix this as it depends on our ISP.

But there’s a way to work around it. The bad news? You’ll need a server, or someone who can lend you some tiny space in one. You could also figure a way to have your IP sent to a service like pastebin, but it wouldn’t be as comfortable because you’d miss the redirection from one simple URL to your localhost Also, terrible news of this method: you’ll need to store your fpt password in plain text in a file in your local machine. This could be avoided using scp, but my hosting doesn’t allow for ssh use so I have to be happy with this.

Anyway. We first need a way to figure out or public IP and upload it to a server. Turns out this is pretty easy with a bash script. It uses a here document code block, which are pretty interesting so you should give that page a read. I took it from this Stackoverflow answer.

#!/usr/bin/env bash
baseIP=$(curl -s icanhazip.com)
echo "$baseIP":5050 > ./myIP
ftp -n *url* <<END
user *user* *password*
binary
cd *folder*
put ./myIP
bye
END
The script uses icanhazip.com, which is very convienen cause it returns your IP without ads or even formatting, just plain text. Once it has your IP, it appends :5050 to the end of it and writes it to the myIP file. The :5050 is there because that's the port Couchpotato uses.
It then open ftp to an url and gives the ftp program the input between <<END and END, line by line. That's the already mentioned here document block.
Of course you should replace url, user, password and folder with your own.
Now, that's very pretty but we haven't achieved much. There's one step missing that will make this very practical. You should have a little php file inside the folder where you upload the file with your IP that redirects the user to the desired IP. Turns out this is pretty simple.
<?php
$myIP = fgets(fopen("myIP", "r")) or die("Unable to open file!");
header("Location: http://$myIP");
?>
And that's it! You could set up redirection so you don't actually have to write the URL to the php file but instead just to a folder for maximum convenience. But that's about it.