If you’ve ever struggled to find the public IP address of a server, especially when you only have CLI access, you’re not alone. There are services out there like ifconfig.me, ipify.org, and others. But personally, the problem I always face is simple: I forget their URLs when I need them, I always need to google the correct curl command.
The good news is, you don’t have to rely on third-party sites. You can build your own lightweight public IP echo service using Cloudflare Workers for free.
- Log in to your Cloudflare account.
- Go to Compute (Workers) -> Workers & Pages -> Create.
- Under “Start with Hello World!”, click Get Started.
- Give your worker a name and click Deploy.
- Once your worker finished deploying, Go to your worker’s page (either from the deploy success screen or via Compute (Workers) -> Workers & Pages).
- Click Edit Code, and replace the default sample with the following:
export default {
async fetch(request) {
return new Response(
request.headers.get("cf-connecting-ip") + "\n",
{ headers: { "content-type": "text/plain" } }
);
}
}
The above code listens for requests to your worker URL, extract the client’s IP from the cf-connecting-ip header which is set by cloudflare and returns it as plain text with a new line. If you are not using cloudflare workers which are usually behind cloudflares Edge (proxy), you can try x-forwarded-for instead of cf-connecting-ip if you are hosing your serverless function behind another revers proxy such as haproxy or nginx. x-forwarded-for can contain multiple IPs separated by comma, depending on how many proxies the request went through.
- Then Click Deploy to save your changes.
- At this point, you can visit your worker’s default URL or run:
curl https://worker_name.username.workers.dev
- That works, but it doesn’t solve my main issue: I always forget the URL.
- To fix this you can assign a custom subdomain you’ll remember.
- Go to your worker’s Settings -> Domain & Routes.
- Click + Add -> Custom Domain.
- Enter an easy to remember domain (for me it was ip.tadiosabebe.com).
- The domain you used in the above step must already be managed in your Cloudflare account (which is free once you have a domain).
That’s it! Now you have your own personal “What’s My IP” service.
Try it for your self. It works in any browser: https://ip.tadiosabebe.com Or from the CLI:
curl https://ip.tadiosabebe.com