in reply to How to detect X?

A cheap and easy way to see if the X server is running is to just try to connect to it. If the connection works, then X is running (probably) otherwise it is not running. (This would fail if some other program is listening to the same port as X uses.)

First, you'll need $ENV{DISPLAY}. If it isn't there, then X is not running. The format of DISPLAY is "hostname:display.screen" where display and screen are numbers, and screen is optional. If hostname is not there, it defaults to localhost. Common settings are "localhost:0" and "localhost:0.0" or just ":0"

Once you have the hostname and the display number, add 6000 to the display number and attempt to make a TCP connection to that port number. If the connection fails, X is not running. If it works, just disconnect immediately and assume you connected to the X server. (For extra credit, you might try sending data into the connection and see if you get the right reply back.)

UPDATE: This method does not always work. The user's X server may not be listening on TCP. When DISPLAY=":0.0" then the "most efficient way of communicating to a server on the same machine" should be used. Usually that means UNIX domain sockets, but it is platform dependent. In this case, the TCP connection fails even though there is a running X server.

Replies are listed 'Best First'.
Re^2: How to detect X?
by gellyfish (Monsignor) on Feb 21, 2005 at 16:03 UTC

    you might try sending data into the connection and see if you get the right reply back

    X11::Protocol might simplify this part ;-)

    /J\

Re^2: How to detect X?
by Anonymous Monk on Feb 21, 2005 at 17:09 UTC
    Once you have the hostname and the display number, add 6000 to the display number and attempt to make a TCP connection to that port number. If the connection fails, X is not running.
    If you have setup X-Windows insecurely (that is, let anyone connect to it - you didn't think that "xhost" is much of a security, do you?), you are right. Sane people start their X-Windows server in such a way it isn't listening to port 6000. Or any other port for that matter.

    X-Windows works fine using Unix domain sockets as well. You just can't display an alien application from elsewhere. Which is a good thing. (Though I have no idea whether X-Windows servers on Windows (sic!) machines can do this).

      To further the argument against leaving X listening to a tcp port, I should point out that using a domain socket doesn't exclude the use of remote X apps. It's fairly easy to get them tunneled through ssh connections back to your display. ssh is smart enough to use xauth cookies for you, too.

      mhoward - at - hattmoward.org
Re^2: How to detect X?
by Anonymous Monk on Feb 21, 2005 at 17:04 UTC
    If it isn't there, then X is not running.
    Yes, but that doesn't mean that if it's there, X is running.

    A implies B doesn't mean B implies A.