简体   繁体   English

如何使用grpc-java从请求元数据中获取客户端ip

[英]How to get client ip from request metadata with grpc-java

I use grpc-java and get the metadata by ServerInterceptor, but i get below information without client ip address, the authority is server ip, how can i get the client ip?Thanks. 我使用grpc-java并通过ServerInterceptor获取元数据,但我得到以下信息没有客户端IP地址,权限是服务器IP,我怎么能得到客户端IP?谢谢。

Metadata({:scheme=[http], :method=[POST], :path=[/test/test1], :authority=[192.168.199.9:50051], grpc-encoding=[identity], grpc-accept-encoding=[identity,deflate,gzip], te=[trailers], content-type=[application/grpc], user-agent=[grpc-objc/0.13.0 grpc-c/0.13.0 (ios)]}) 元数据({:scheme = [http],:method = [POST],:path = [/ test / test1],:authority = [192.168.199.9:50051],grpc-encoding = [identity],grpc-accept- encoding = [identity,deflate,gzip],te = [trailers],content-type = [application / grpc],user-agent = [grpc-objc / 0.13.0 grpc-c / 0.13.0(ios)]} )

Client IP is not provided in Metadata. 元数据中未提供客户端IP。 But you can call ServerCall.attributes() and get the Grpc.TRANSPORT_ATTR_REMOTE_ADDR . 但是您可以调用ServerCall.attributes()并获取Grpc.TRANSPORT_ATTR_REMOTE_ADDR

Please note that the API is unstable and may change. 请注意,API不稳定,可能会发生变化。

在最新的(1.2.0)gRPC中使用拦截器中的io.grpc.Grpc.TRANSPORT_ATTR_REMOTE_ADDR属性来获取远程地址。

if in python grpc, you will get client ip address and port using context.peer() . 如果在python grpc中,您将使用context.peer()获取客户端IP地址和端口。

def your_method(self, request, context):
    ...
    context.peer() # return 'ipv4:49.123.106.100:44420'
    ...

Client IP is exposed as gRPC attributes (TRANSPORT_ATTR_REMOTE_ADDR), an example of accessing it is here 客户端IP作为gRPC属性公开(TRANSPORT_ATTR_REMOTE_ADDR),访问它的示例在这里

 String inetSocketString = serverCallCapture.get().getAttributes()
    .get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR).toString();

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

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