public static byte [ ] getOsVersion ( ) { String os = System . getProperty ( "os.name" ) ; if ( os == null || ! os . toUpperCase ( ) . contains ( "WINDOWS" ) ) { return DEFAULT_OS_VERSION ; } byte [ ] osVer = new byte [ 8 ] ; // Let's enclose the code by a try...catch in order to // manage incorrect strings. In this case, we will generate // an exception and deal with the special cases. try { Process pr = Runtime . getRuntime ( ) . exec ( "cmd /C ver" ) ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( pr . getInputStream ( ) ) ) ; pr . waitFor ( ) ; String line ; // We loop as we may have blank lines. do { line = reader . readLine ( ) ; } while ( ( line != null ) && ( line . length ( ) != 0 ) ) ; reader . close ( ) ; // If line is null, we must not go any farther if ( line == null ) { // Throw an exception to jump into the catch() part throw new Exception ( ) ; } // The command line should return a response like : // Microsoft Windows XP [version 5.1.2600] int pos = line . toLowerCase ( ) . indexOf ( "version" ) ; if ( pos == - 1 ) { // Throw an exception to jump into the catch() part throw new Exception ( ) ; } pos += 8 ; line = line . substring ( pos , line . indexOf ( ' ' ) ) ; StringTokenizer tk = new StringTokenizer ( line , "." ) ; if ( tk . countTokens ( ) != 3 ) { // Throw an exception to jump into the catch() part throw new Exception ( ) ; } writeOSVersion ( Byte . parseByte ( tk . nextToken ( ) ) , Byte . parseByte ( tk . nextToken ( ) ) , Short . parseShort ( tk . nextToken ( ) ) , osVer , 0 ) ; } catch ( Exception ex ) { try { String version = System . getProperty ( "os.version" ) ; writeOSVersion ( Byte . parseByte ( version . substring ( 0 , 1 ) ) , Byte . parseByte ( version . substring ( 2 , 3 ) ) , ( short ) 0 , osVer , 0 ) ; } catch ( Exception ex2 ) { return DEFAULT_OS_VERSION ; } } return osVer ; }
Tries to return a valid OS version on Windows systems . If it fails to do so or if we re running on another OS then a fake Windows XP OS version is returned because the protocol uses it .