How to tell if running in a linux console versus an ssh session?

Stéphane picture Stéphane · May 25, 2010 · Viewed 7k times · Source

I have an application that needs to behave differently if run directly from the linux console. So if a user connects with SSH to run FooBar, or the user walks over to the console and logs in directly to run FooBar, I want it to do something different.

What C API do I need to call to tell the difference between these two scenarios? I was thinking I'd have to look at the "tty/pts" information (such as what I see when I run "ps axf"), but I'm not certain if that is the best solution, nor what API to call to get that information.

Hints appreciated. :)

Answer

developmentalinsanity picture developmentalinsanity · May 25, 2010

Depending on how much you're worried about it being spoofed, an easy check would be for the presence/absence of the SSH_CLIENT and SSH_CONNECTION environment variables, in which case you'd want the getenv function.