How to programmatically (C/C++) verify if X11 forwarding is enabled?

284 views Asked by At

The application is run remotely on target hardware. User can choose to enable visual debug output (using command line switches) in that case a ssh's X11 forwarding is used to view it.

The problem starts if user forgets to establish the connection before running the application like this: ssh -YC remote.host. The application will crash.

I would like to detect this situation beforehand and print proper message while starting the application. Is it possible to do it in C/C++? In the worst case I can execute some shell commands in the background.

2

There are 2 answers

0
Henrique Bucher On BEST ANSWER

You could use XOpenDisplay man page

#include <X11/Xlib.h>
#include <cstdlib>
#include <iostream>

bool displayIsValid()
{
    char* disp = getenv("DISPLAY");
    if ( disp==nullptr ) return false;
    Display* dpy = XOpenDisplay(disp);  
    if ( dpy==nullptr ) return false;
    XCloseDisplay(dpy);
    return true;
}

int main() {
    if ( displayIsValid() ) {
        std::cout << "Display is valid" << std::endl;
    }
}
1
teapot418 On

If you have an X11 display (real or forwarded by ssh), you have a DISPLAY environment variable. Otherwise it should not be present.

The least invasive check is probably:

if (!getenv("DISPLAY")) {
    fprintf(stderr, "missing X11 display, have you forgotten something?\n");
    exit(1);
}

This should trigger just fine if someone forgets X forwarding in ssh.