import java.net.*; import java.io.*; public class DirectCupsConnection { public static void main(String[] args) throws Exception { System.out.println("Direct CUPS Socket Connection Test"); // Connect to CUPS socket Socket socket = new Socket(); try { // Try UNIX socket first socket.connect(new InetSocketAddress("localhost", 631)); System.out.println("Connected to CUPS on port 631"); // Send IPP request to get printers String ippRequest = "POST / HTTP/1.1\r\n" + "Host: localhost:631\r\n" + "Content-Type: application/ipp\r\n" + "Connection: close\r\n\r\n"; OutputStream out = socket.getOutputStream(); out.write(ippRequest.getBytes()); out.flush(); // Read response BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); String line; System.out.println("\nCUPS Response:"); int count = 0; while ((line = in.readLine()) != null && count++ < 20) { if (line.contains("printer") || line.contains("Printer") || line.contains("device") || line.contains("URI")) { System.out.println(line); } } } catch (ConnectException e) { System.out.println("Could not connect to CUPS on port 631"); System.out.println("Trying UNIX socket..."); // Try UNIX domain socket try { // Java doesn't natively support UNIX sockets, so use a different approach ProcessBuilder pb = new ProcessBuilder("lpstat", "-v"); Process p = pb.start(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); System.out.println("\nPrinters from lpstat:"); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e2) { System.err.println("Error: " + e2.getMessage()); } } finally { socket.close(); } } }