8

I set up a series of gRPC requests and responses which all work fine, but I'm stuck when I try to get the client IP address and user-agent who is calling my gRPC APIs.

I read the Go gRPC documentation and other sources, but didn't find much valuable information. Few of them are talking about gRPC in Golang.

Should I set up a key-value to store the IP address in the context when setting up the gRPC APIs?

Vitaly Isaev
  • 5,392
  • 6
  • 45
  • 64
Felix
  • 113
  • 1
  • 1
  • 5

3 Answers3

24

In Golang GRPC, you can use

func (UserServicesServer) Login(ctx context.Context, request *sso.LoginRequest) (*sso.LoginResponse, error) {
  p, _ := peer.FromContext(ctx)
  request.Frontendip = p.Addr.String()
  .
  .
}

But, do not forget import "google.golang.org/grpc/peer"

Yang
  • 7,712
  • 9
  • 48
  • 65
mbdrian
  • 451
  • 4
  • 11
2

For grpc-gateway is used, the client IP address may be retrieved through x-forwarded-for like this:

// Get IP from GRPC context
func GetIP(ctx context.Context) string {
    if headers, ok := metadata.FromIncomingContext(ctx); ok {
        xForwardFor := headers.Get("x-forwarded-for")
        if len(xForwardFor) > 0 && xForwardFor[0] != "" {
            ips := strings.Split(xForwardFor[0], ",")
            if len(ips) > 0 {
                clientIp := ips[0]
                return clientIp
            }
        }
    }
    return ""
}
Amin Shojaei
  • 5,451
  • 2
  • 38
  • 46
zangw
  • 43,869
  • 19
  • 177
  • 214
0

In Golang GRPC, context has 3 values

  1. authority

  2. content-type

  3. user-agent

    md,ok:=metadata.FromIncomingContext(ctx)
    fmt.Printf("%+v%+v",md,ok)
    
morteza khadem
  • 346
  • 3
  • 8