繁体   English   中英

Java 中的 Azure 函数 - 获取远程地址 IP

[英]Azure functions in Java - Get remote address IP

我正在寻找一种在 Java 中的 Azure 函数中获取远程 IP 地址的解决方案。 来自 HttpRequestMessage 的标头仅包含主机。 我找到了 .NET 的解决方案,但像往常一样,Java 更难。

您可以从请求头x-forwarded-for 中获取 IP:

@FunctionName("test")
public HttpResponseMessage getConfig(
    @HttpTrigger(
        name = "request",
        methods = {HttpMethod.GET},
        route = "test",
        authLevel = AuthorizationLevel.ANONYMOUS
    ) HttpRequestMessage<Optional<String>> request,
    ExecutionContext context
) {
    // Prints all headers
    for (Map.Entry<String, String> header : request.getHeaders().entrySet()) {
        context.getLogger().info(header.getKey() + " - " + header.getValue());
    }
    // Prints the header containing the IP address in the format ip:port
    context.getLogger().info(request.getHeaders().get("x-forwarded-for"));
    
    ...
}

请注意,IP 地址附带了一个端口。 例如:123.123.213.213:88999

所以你只需要对字符串进行处理以删除端口部分。

注意: x-forwarded-for 标头仅存在于真实的 Azure Functions 环境中。 如果您在本地环境中测试它,您将找不到这样的标头。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM