简体   繁体   English

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

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

I'm looking for a solution to get the remote IP address in an Azure function in Java.我正在寻找一种在 Java 中的 Azure 函数中获取远程 IP 地址的解决方案。 The headers from the HttpRequestMessage contains only the host.来自 HttpRequestMessage 的标头仅包含主机。 I've found a solution for .NET but as usual, more difficult for Java.我找到了 .NET 的解决方案,但像往常一样,Java 更难。

You can get the IP from the request header x-forwarded-for :您可以从请求头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"));
    
    ...
}

Note that the IP address comes with a port attached.请注意,IP 地址附带了一个端口。 Ex: 123.123.213.213:88999例如:123.123.213.213:88999

So you just need do proccess the string to remove the port portion.所以你只需要对字符串进行处理以删除端口部分。

NOTE: the x-forwarded-for header only exists in the real Azure Functions environment.注意: x-forwarded-for 标头仅存在于真实的 Azure Functions 环境中。 If you test it in your local environment you will not find such header.如果您在本地环境中测试它,您将找不到这样的标头。

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

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