Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to read IP connection header inside server application in go?

Tags:

go

grpc-go

Server application supports authentication which demands username and password from the client who is connecting with it. There can be a client from within the machine as well for which I do not want it to be authenticated. Client within the same machine connects with the server with the LOOPBACK address. What I want is that, if I can somehow apply filter for the destination IP of the gRPC connection and decide whether to apply authentication or not. Is there a way? Thanks !

func (s *RShellServer) ExecCmd(stream RShell_ExecCmdServer) error {
    # For example, something like this if condition.
    if (Conn().destination_ip != LOOPBACK) {
        if err, ok := gnmi.AuthorizeUser(stream.Context()); !ok {
                return fmt.Errorf("%s", err)
        }
    }
    req, err := stream.Recv()
    if err != nil {
        return fmt.Errorf("Error reading request: %s", err)
    }
}
like image 202
TheChosenOne Avatar asked Nov 22 '25 22:11

TheChosenOne


1 Answers

Your GRPC service should be something like this

func (MyServer) SomeFunction(ctx context.Context, 
    req *myserver.Request) (resp *myserver.Response, err error)

Then you can use peer library and extract peer information from context like `

p, err := peer.FromContext(ctx)

And get address from peer using

p.Addr
like image 68
Shubham Srivastava Avatar answered Nov 25 '25 13:11

Shubham Srivastava