Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine current glibc version from within Java

Tags:

java

linux

glibc

For a java application running on a linux system, how can I determine the underlying version of glibc?

Background: I'd like to, at runtime, determine if it possible to use conscrypt, which appears to require glibc 2.14 nowadays (https://github.com/google/conscrypt/pull/589), but I would still need to gracefully support running on CentOS 6 or other older distributions by falling back to the standard Java SSL code. Unfortunately (at least as far as I've been able to determine) there's no way to catch and recover from the error that occurs if Conscrypt is initialised on an older distribution, but if I can determine the glibc version I could choose whether to initialise it based on that.

like image 349
Matt Sheppard Avatar asked Sep 19 '26 10:09

Matt Sheppard


1 Answers

Working example of executing ldd --version and parsing the response for the version number.

public class Main {

    public static void main(String[] args) throws IOException {
        final ProcessBuilder processBuilder = new ProcessBuilder("/bin/bash").command("ldd --version");
        processBuilder.redirectErrorStream(true);

        final Process process = processBuilder.start();
        final StringBuilder stream = readStream(process.getInputStream());

        final String version = getVersion(stream.toString());

        System.out.println(version);
    }

    /**
     * Read the output stream of the process
     *
     * @param iStream InputStream
     * @return StringBuilder containing the output of the command
     */
    private static StringBuilder readStream(InputStream iStream) throws IOException {
        final StringBuilder builder = new StringBuilder();
        String line;

        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(iStream))) {
            while ((line = bufferedReader.readLine()) != null) {
                builder.append(line);
                builder.append(System.getProperty("line.separator"));
            }
        }

        return builder;
    }

    /**
     * Parse the response for the version number.
     *
     * @param input String response of ldd --version
     * @return String of the version, or null if not found
     */
    private static String getVersion(String input) {
        final Pattern pattern = Pattern.compile("[-+]?[0-9]*\\.?[0-9]+");
        final Matcher matcher = pattern.matcher(input);

        return matcher.find() ? matcher.group() : null;
    }
}
like image 55
Chris Turner Avatar answered Sep 20 '26 23:09

Chris Turner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!