Sure, here’s the translation: 在Java中使用Azure Functions – 获取远程地址IP

huangapple go评论73阅读模式
英文:

Azure functions in Java - Get remote address IP

问题

我正在寻找在Java中的Azure函数中获取远程IP地址的解决方案。来自HttpRequestMessage的标头仅包含主机信息。我已经找到了.NET的解决方案,但通常情况下,Java的解决方案较为复杂。

英文:

I'm looking for a solution to get the remote IP address in an Azure function in Java. The headers from the HttpRequestMessage contains only the host.
I've found a solution for .NET but as usual, more difficult for Java.

答案1

得分: 1

你可以从请求头 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
) {
    // 打印所有头部信息
    for (Map.Entry<String, String> header : request.getHeaders().entrySet()) {
        context.getLogger().info(header.getKey() + " - " + header.getValue());
    }
    // 打印包含IP地址(格式为ip:port)的头部信息
    context.getLogger().info(request.getHeaders().get("x-forwarded-for"));
    
    ...
}

需要注意的是,IP地址附带有端口号。例如:
123.123.213.213:88999

因此,你只需要处理字符串以删除端口部分。

注意:x-forwarded-for 头部信息仅在真实的Azure Functions环境中存在。如果你在本地环境中进行测试,将找不到这样的头部信息。

英文:

You can get the IP from the request header x-forwarded-for:

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

Note that the IP address comes with a port attached. Ex:
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. If you test it in your local environment you will not find such header.

huangapple
  • 本文由 发表于 2020年10月22日 04:47:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/64471522.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定