7

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,080
  • 5
  • 42
  • 61
Felix
  • 103
  • 1
  • 5

3 Answers3

16

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,312
  • 7
  • 45
  • 64
mbdrian
  • 371
  • 3
  • 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
  • 3,796
  • 2
  • 27
  • 38
zangw
  • 37,361
  • 17
  • 142
  • 172
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
  • 316
  • 2
  • 7