Original link: https://blog.est.im/2022/stdout-09
When I saw a post that returned the IP and port number used for client connection , I also needed to be familiar with Cloudflare workers, so I used it to practice my skills.
export default { async fetch(request, env) { return await handleRequest(request).catch( (err) => new Response(err.stack, { status: 500 }) ) } } async function handleRequest(request) { const { pathname } = new URL(request.url); if (pathname === "/ip") { const ip = request.headers.get('CF-Connecting-IP'); return new Response(ip + '\n'); } if (pathname === "/ip:port") { const ip = request.headers.get('CF-Connecting-IP'); const port = request.headers.get('est-Connecting-Port') || '?' return new Response(ip + ':' + port + '\n'); } return new Response('Tools:\n /ip\n/ip:port\n'); }
Encountered a problem, Cloudflare officially provides the browser client IP variable CF-Connecting-IP
but lacks the port. After checking, you can get it through the variable cf.edge.client_port
by entering the CF website management panel → Rules → Add a request header rule to Transform Rules → HTTP Request Header Modification. As shown in the figure:
But the header cannot start with CF-
, so change it to est-Connecting-Port
here, you can get the IP+port requested by the client
Test address: t. The root domain name of this website/ip:port
Currently missing: a proper representation of IPv6. . . .
This article is reproduced from: https://blog.est.im/2022/stdout-09
This site is for inclusion only, and the copyright belongs to the original author.