kitex icon indicating copy to clipboard operation
kitex copied to clipboard

how to get peer info by stream context in stream grpc server

Open zanlichard opened this issue 5 months ago • 1 comments

peer.GetPeerFromContext can't get client ip and port info

zanlichard avatar Jul 01 '25 07:07 zanlichard

The issue occurs because peer.GRPCPeer only sets peer information in the client-side context locally and doesn't transmit it over the network.

Recommended: In Kitex, the correct way to get peer information in gRPC Stream Server is through rpcinfo:

func (s *EchoImpl) Echo(ctx context.Context, req *api.Request) (resp *api.Response, err error) {
    // Get client connection info
    ri := rpcinfo.GetRPCInfo(ctx)
    if ri != nil && ri.From() != nil && ri.From().Address() != nil {
        clientAddr := ri.From().Address().String()
        fmt.Printf("Client address: %s\n", clientAddr)
    }
    
    return &api.Response{Message: "success"}, nil
}

Technical Details: rpcinfo fields are explicitly encoded in protocol headers during transmission:

// Client side: rpcinfo fields are encoded to HTTP2 headers
md.Append("source-service", ri.From().ServiceName())
md.Append("source-method", ri.From().Method())
// ... and connection info is captured from real TCP connection

// Server side: Framework rebuilds rpcinfo from headers + connection info
// rpcinfo.GetRPCInfo(ctx) provides real client address ✅

Additional Options: For custom peer information transmission, use metainfo:

// Client side
ctx = metainfo.WithValue(ctx, "custom_info", "value")

// Server side  
if customInfo, ok := metainfo.GetValue(ctx, "custom_info"); ok {
    fmt.Printf("Custom info: %s\n", customInfo)
}

XinyiWang0204 avatar Jul 07 '25 02:07 XinyiWang0204