英文:
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("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. 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论