'How can I get the client IP address and user-agent in Golang gRPC?

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?



Solution 1:[1]

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"

Solution 2:[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 ""
}

Solution 3:[3]

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)
    

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yang
Solution 2 Amin Shojaei
Solution 3 morteza khadem