### Install Build Dependencies Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/graalvm.md Install necessary system-level dependencies for building native images. ```bash ## Add dependencies if necessary, e.g.: sudo apt-get install gcc zlib1g-dev ``` -------------------------------- ### Run Demo Script Syntax and Examples Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/demo.md Illustrates the syntax and provides examples for running specific junixsocket demos using the run-demo.sh script. This includes launching server, client, RMI, MySQL, PostgreSQL, and HTTP server demos, with options for specifying jars and Java system properties. ```bash $ ./run-demo.sh Syntax: ./run-demo.sh [-m] [-j jar]+ [-- [java opts]*] Example: # Runs the demo server ./run-demo.sh org.newsclub.net.unix.demo.SimpleTestServer # Runs the demo client ./run-demo.sh org.newsclub.net.unix.demo.SimpleTestClient # Runs the demo RMI server ./run-demo.sh org.newsclub.net.unix.demo.rmi.SimpleRMIServer # Runs the demo RMI client ./run-demo.sh org.newsclub.net.unix.demo.rmi.SimpleRMIClient # Runs the demo server. Replace "(demo)" with the desired demo. ./run-demo.sh -- -Ddemo=(demo) org.newsclub.net.unix.demo.server.AFUNIXSocketServerDemo # Runs the demo client. Replace "(demo)" with the desired demo, and "(socket)" with the socket to connect to. ./run-demo.sh -- -Ddemo=(demo) -Dsocket=(socket) org.newsclub.net.unix.demo.client.DemoClient # Runs the MySQL demo ./run-demo.sh -j (path-to-mysql-connector-jar) -- -DmysqlSocket=/tmp/mysql.sock org.newsclub.net.mysql.demo.AFUNIXDatabaseSocketFactoryDemo # Runs the PostgreSQL demo ./run-demo.sh -j (path-to-postgresql-jar) -- -DsocketPath=/tmp/.s.PGSQL.5432 org.newsclub.net.unix.demo.jdbc.PostgresDemo # Runs the HTTP Server ./run-demo.sh -j (path-to-nanohttpd-jar) -- org.newsclub.net.unix.demo.nanohttpd.NanoHttpdServerDemo Other flags: -m Use the Java module-path instead of the classpath (Java 9 or higher) -j Add the given jar to the beginning of the classpath/modulepath -- Separate the run-demo flags from the Java JVM flags ``` -------------------------------- ### Install crossclang SDK for Xcode Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/xcode.md Executes the installation script to link the crossclang SDK into the Xcode toolchain directory. ```bash ./junixsocket-native/crossclang/Xcode-Support/install ``` -------------------------------- ### Install Development Tools on Alpine Linux Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/building.md Installs essential development tools including git, Maven, clang, gcc, binutils, bash, and C/Linux headers on Alpine Linux. This is a prerequisite for compiling C code. ```bash sudo apk add git maven clang gcc binutils bash musl-dev libc-dev linux-headers ``` -------------------------------- ### Run Junixsocket Demos Script Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/demo.md Use the run-demos.sh script to launch various junixsocket examples. The script accepts a classname as an argument and can be configured with Java options. ```bash ./run-demos.sh ``` -------------------------------- ### Enable musl Compatibility on Alpine Linux Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/graalvm.md Install gcompat to ensure the native binary runs on Alpine Linux systems. ```bash sudo apk add gcompat ``` -------------------------------- ### Install LLVM and LLD on macOS Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/crosscomp.md On macOS, the Xcode version of clang is insufficient for cross-compilation. Install llvm and lld using Homebrew. ```bash brew install llvm lld ``` -------------------------------- ### Configure GraalVM Environment Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/graalvm.md Set the JAVA_HOME and PATH environment variables to point to your GraalVM installation. ```bash # export JAVA_HOME=/Library/Java/JavaVirtualMachines/graalvm-ce-java17-22.2.0/Contents/Home # export PATH=$JAVA_HOME/bin:$PATH ``` -------------------------------- ### Build and Test junixsocket Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/building.md Compiles, tests, and installs junixsocket using Maven. The second command shows how to disable the retrolambda plugin if JDK 8 is not installed. ```bash mvn clean install ``` ```bash mvn clean install -Dretrolambda=false ``` -------------------------------- ### Simple C test program Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/crosscomp.md A basic C program that prints 'Hello world, crossclang style!' to the console. This can be used to test cross-compilation setups. ```c #include int main(int argc, char *argv[]) { printf("Hello world, crossclang style!\n"); return 0; } ``` -------------------------------- ### Websocket to Unix Socket with websocat Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/unixsockets.md Forward data between a WebSocket and a Unix domain socket using websocat. This example shows a WebSocket listening on a local address and forwarding to a Unix socket. ```bash websocat ws-l:127.0.0.1:8088 unix:the_socket ``` -------------------------------- ### Unix Socket Listen to Websocket with websocat Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/unixsockets.md Forward data from a Unix domain socket to a WebSocket using websocat. This example listens on a Unix socket and forwards to a WebSocket server. ```bash websocat --unlink unix-l:the_socket ws://127.0.0.1:8089 ``` -------------------------------- ### Get Standard FileDescriptors Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/filedescriptors.md Access the standard input, output, and error FileDescriptors provided by the Java runtime. ```java // Standard file descriptors FileDescriptor stdin = FileDescriptor.in; FileDescriptor stdout = FileDescriptor.out; FileDescriptor stderr = FileDescriptor.err; ``` -------------------------------- ### Configure JDK 8 Toolchain for Maven Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/building.md Specifies the JDK 8 installation path in Maven's toolchains.xml file. This is required for building junixsocket with Java 7 compatibility via the retrolambda plugin. ```xml jdk 1.8 /Library/Java/JavaVirtualMachines/1.8.0.jdk/Contents/Home/ ``` -------------------------------- ### Unix Domain Socket NIO Client Operations (Java) Source: https://context7.com/kohlschutter/junixsocket/llms.txt Perform non-blocking I/O operations on Unix domain sockets using AFUNIXSocketChannel. This example shows how to open a channel, write data, and read responses. ```java import org.newsclub.net.unix.AFUNIXSocketChannel; import org.newsclub.net.unix.AFUNIXSocketAddress; import java.io.File; import java.nio.ByteBuffer; AFUNIXSocketAddress addr = AFUNIXSocketAddress.of(new File("/tmp/nio.sock")); // Open and connect a channel directly try (AFUNIXSocketChannel channel = AFUNIXSocketChannel.open(addr)) { ByteBuffer buffer = ByteBuffer.allocate(1024); buffer.put("Hello via NIO!".getBytes()); buffer.flip(); channel.write(buffer); buffer.clear(); int bytesRead = channel.read(buffer); buffer.flip(); byte[] data = new byte[bytesRead]; buffer.get(data); System.out.println("Received: " + new String(data)); } ``` -------------------------------- ### Build Everything (Current Architecture) Source: https://github.com/kohlschutter/junixsocket/blob/main/BUILDING.md Use this command to perform a full build for your current system architecture. It compiles all modules and includes the native library. ```bash mvn clean install ``` -------------------------------- ### Prepare Target SDK for Cross-compilation Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/crosscomp.md Use the `prepare-target-sdk` script to automatically generate an SDK from a target machine. This script should be run on all target platforms, including the development machine. The generated SDKs are stored in `junixsocket-native/crosslang/target-sdks/` and should be copied to a shared directory on the development machine. ```bash junixsocket-native/crossclang/bin/prepare-target-sdk ``` -------------------------------- ### Build and Run Native Image Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/graalvm.md Commands to build the native image using Maven and execute the resulting binary. ```bash # Build the platform-native executable: cd junixsocket/junixsocket-selftest-native-image # (Also specify -Dmysql to include junixsocket-mysql tests) mvn -Dnative clean package # Run the platform-native executable: ./target/junixsocket-selftest-native-image-X.Y.Z ``` -------------------------------- ### Create a Listening Unix Socket with netcat Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/unixsockets.md Use 'nc -lU /path/to/socket' to create a listening Unix domain stream socket. ```bash nc -lU /path/to/socket ``` -------------------------------- ### Get FileDescriptor from FileInputStream Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/filedescriptors.md Obtain the FileDescriptor associated with a FileInputStream. This allows access to the underlying file handle. ```java FileInputStream in = ...; FileDescriptor fd = in.getFD(); ``` -------------------------------- ### Get FileDescriptor from RandomAccessFile Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/filedescriptors.md Retrieve the FileDescriptor from a RandomAccessFile. This provides access to the file's underlying system handle. ```java RandomAccessFile raf = ...; FileDescriptor fd = in.getFD(); ``` -------------------------------- ### Connect to a Unix Socket with netcat Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/unixsockets.md Use 'nc -U /path/to/socket' to connect to an existing Unix domain stream socket. ```bash nc -U /path/to/socket ``` -------------------------------- ### Get FileDescriptor from AFSocket Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/filedescriptors.md Retrieve the FileDescriptor from an AFSocket instance. This is useful when working with junixsocket's advanced socket features. ```java AFSocket socket = ...; FileDescriptor fd = socket.getFileDescriptor(); ``` -------------------------------- ### Build junixsocket demo with jlink and jpackage Source: https://github.com/kohlschutter/junixsocket/blob/main/junixsocket-demo-jpackagejlink/README.md Execute the Maven build process with specific profiles enabled to generate jlink and jpackage artifacts. ```bash cd junixsocket-demo-jpackagejlink mvn clean verify -Djpackage -Djlink ``` -------------------------------- ### Build junixsocket-native via command-line Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/xcode.md Uses xcodebuild to compile the project with the crossclang toolchain from the terminal. ```bash xcodebuild -project junixsocket-native/junixsocket-native.xcodeproj -configuration Release \ -target "All Architectures" -toolchain crossclang USE_HEADERMAP=NO \ CURRENT_ARCH=undefined_arch arch=undefined_arch ARCHS=arm64 CODE_SIGNING_ALLOWED=NO \ clean build ``` -------------------------------- ### Build Quickly (Ignoring Quality) Source: https://github.com/kohlschutter/junixsocket/blob/main/BUILDING.md This command prioritizes build speed over code quality checks. It disables Retrolambda and excludes the native library, suitable for rapid local builds. ```bash mvn clean install -Dretrolambda=false -rf :junixsocket-common -Dignorant ``` -------------------------------- ### Connect to Unix Domain Sockets as Client (Java) Source: https://context7.com/kohlschutter/junixsocket/llms.txt Connect to a Unix domain socket server using the AFUNIXSocket API. Demonstrates both direct connection and instance-based connection methods for client sockets. Ensure the server socket file exists. ```java import org.newsclub.net.unix.AFUNIXSocket; import org.newsclub.net.unix.AFUNIXSocketAddress; import java.io.File; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.StandardCharsets; File socketFile = new File("/tmp/my-server.sock"); AFUNIXSocketAddress addr = AFUNIXSocketAddress.of(socketFile); // Connect directly to an address try (AFUNIXSocket socket = AFUNIXSocket.connectTo(addr); InputStream is = socket.getInputStream(); OutputStream os = socket.getOutputStream()) { // Read server greeting byte[] buf = new byte[128]; int read = is.read(buf); System.out.println("Server says: " + new String(buf, 0, read, StandardCharsets.UTF_8)); // Send response os.write("Hello from client!".getBytes(StandardCharsets.UTF_8)); os.flush(); } // Alternative: create socket instance first, then connect try (AFUNIXSocket socket = AFUNIXSocket.newInstance()) { socket.connect(addr); try (DataInputStream din = new DataInputStream(socket.getInputStream()); DataOutputStream dout = new DataOutputStream(socket.getOutputStream())) { dout.writeInt(42); dout.flush(); int response = din.readInt(); System.out.println("Response: " + response); } } ``` -------------------------------- ### RMI Server using AFUNIXNaming Source: https://context7.com/kohlschutter/junixsocket/llms.txt Sets up an RMI server that uses AFUNIXNaming for communication over Unix domain sockets. Ensure the AFUNIXNaming instance is obtained and the registry is created before exporting and binding services. ```java import org.newsclub.net.unix.rmi.AFUNIXNaming; import org.newsclub.net.unix.rmi.AFRegistry; import java.io.IOException; import java.rmi.Remote; import java.rmi.RemoteException; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; // Define a remote interface interface Calculator extends Remote { int add(int a, int b) throws RemoteException; int multiply(int a, int b) throws RemoteException; } // Implement the remote interface class CalculatorImpl implements Calculator { public int add(int a, int b) { return a + b; } public int multiply(int a, int b) { return a * b; } } // RMI Server public class RMIServer { public static void main(String[] args) throws Exception { // Get the default AFUNIXNaming instance AFUNIXNaming naming = AFUNIXNaming.getInstance(); // Create and start the RMI registry naming.createRegistry(); System.out.println("Registry created at: " + naming.getRegistrySocketFile()); // Export and bind the service Calculator calc = new CalculatorImpl(); naming.exportAndBind("calculator", calc); System.out.println("Calculator service bound and ready!"); } } ``` -------------------------------- ### Create a new AF_UNIX Server Socket Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/quickstart.md Use this to create and bind a new AF_UNIX domain server socket to a specified file path. The server socket will listen for incoming connections on this path. ```java File socketFile = new File("/path/to/your/socket"); AFUNIXServerSocket server = AFUNIXServerSocket.newInstance(); server.bind(AFUNIXSocketAddress.of(socketFile)); ``` -------------------------------- ### Create AFUNIXServerSocket Source: https://context7.com/kohlschutter/junixsocket/llms.txt Initialize and bind server sockets to accept incoming Unix domain socket connections, with options for automatic file cleanup. ```java import org.newsclub.net.unix.AFUNIXServerSocket; import org.newsclub.net.unix.AFUNIXSocket; import org.newsclub.net.unix.AFUNIXSocketAddress; import java.io.File; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.StandardCharsets; File socketFile = new File("/tmp/my-server.sock"); AFUNIXSocketAddress addr = AFUNIXSocketAddress.of(socketFile); // Create and bind a server socket try (AFUNIXServerSocket server = AFUNIXServerSocket.newInstance()) { server.bind(addr); System.out.println("Server listening on: " + socketFile); while (!server.isClosed()) { // Accept client connections try (AFUNIXSocket client = server.accept(); InputStream is = client.getInputStream(); OutputStream os = client.getOutputStream()) { System.out.println("Client connected: " + client); // Send greeting os.write("Hello from server!".getBytes(StandardCharsets.UTF_8)); os.flush(); // Read response byte[] buf = new byte[128]; int read = is.read(buf); if (read > 0) { System.out.println("Received: " + new String(buf, 0, read, StandardCharsets.UTF_8)); } } } } // Alternative: bind directly on creation with auto-delete on close try (AFUNIXServerSocket server = AFUNIXServerSocket.bindOn(socketFile.toPath(), true)) { // Socket file will be deleted when server closes AFUNIXSocket client = server.accept(); // handle client... } ``` -------------------------------- ### Build Quickly (Ignoring Tests) Source: https://github.com/kohlschutter/junixsocket/blob/main/BUILDING.md This command is optimized for speed by skipping all test executions. It also disables Retrolambda, excludes the native library, and ignores code quality checks. ```bash mvn clean install -Dretrolambda=false -rf :junixsocket-common -Dignorant -DskipTests ``` -------------------------------- ### Connect to an AF_UNIX Socket Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/quickstart.md Use this to connect to an existing AF_UNIX domain socket. Ensure the socket file exists before attempting to connect. ```java File socketFile = new File("/path/to/your/socket"); AFUNIXSocket sock = AFUNIXSocket.newInstance(); sock.connect(AFUNIXSocketAddress.of(socketFile)); ``` -------------------------------- ### List Listening Unix Sockets with netstat Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/unixsockets.md Use 'netstat --unix -l' to display listening Unix domain sockets. ```bash netstat --unix -l ``` -------------------------------- ### Work with AF_UNIX SocketChannels Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/quickstart.md This snippet demonstrates opening an AFUNIXSocketChannel, connecting it to a socket address, and then accessing the underlying Socket API. It highlights the interchangeability between SocketChannel and Socket APIs with junixsocket. ```java AFUNIXSelectorProvider provider = AFUNIXSelectorProvider.provider(); AFUNIXSocketChannel sc = provider.openSocketChannel(); sc.connect(AFUNIXSocketAddress.of(new File("/tmp/test.sock"))); // (work with SocketChannel API) AFUNIXSocket socket = sc.socket(); // this always succeeds [1] // (work with Socket API) AFUNIXSocket sock = ...; sock.getChannel(); // this always succeeds as well [1] AbstractSelector selector = provider.openSelector(); // work with Selector API ``` -------------------------------- ### Instantiate AFSocketServerConnector Source: https://github.com/kohlschutter/junixsocket/blob/main/junixsocket-jetty/README.md Configure a server connector for junixsocket by providing the server instance and socket address. ```java AFSocketServerConnector connector = new AFSocketServerConnector(server, acceptors, selectors, new HttpConnectionFactory()); AFSocketAddr afAddr = ...; // e.g., AFUNIXSocketAddress.of(new File("/tmp/sock)); connector.setListenSocketAddress(afAddr); // (optional) try to automatically stop server if another instance reuses our address connector.setMayStopServer(true); server.addConnector(connector); ``` -------------------------------- ### List Unix Sockets via /proc/net/unix (Linux) Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/unixsockets.md On Linux, the '/proc/net/unix' file provides a list of all active Unix domain sockets. ```bash cat /proc/net/unix ``` -------------------------------- ### Build junixsocket selftest with GraalVM Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/graalvm.md Shell script to configure the environment and execute the selftest build process for GraalVM native-image compatibility. ```bash # Make sure GraalVM is enabled, e.g.: export JAVA_HOME=/Library/Java/JavaVirtualMachines/graalvm-ce-java17-22.2.0/Contents/Home export PATH=$JAVA_HOME/bin:$PATH # Run selftest with native-image-gent, build and run native-image version of selftest cd junixsocket/junixsocket-native-graalvm bin/build-selftest ``` -------------------------------- ### List Unix Sockets with lsof Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/unixsockets.md Use 'lsof -U' to list all Unix domain sockets. Add '+E' for peer process information on Linux. ```bash lsof -U ``` ```bash lsof +E -U ``` ```bash sudo lsof -a -U -u root ``` -------------------------------- ### Build junixsocket with SNAPSHOT Dependencies Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/building.md Builds junixsocket using SNAPSHOT versions of its dependencies. This is typically needed for development versions. ```bash mvn clean install -Duse-snapshots ``` -------------------------------- ### Using crossclang from Command-line Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/crosscomp.md The `crossclang` script simplifies configuring the compiler and linker for a specific target environment. It forwards arguments to `clang` and automatically configures sysroot, include paths, library paths, and the appropriate linker based on the `-target` argument. ```bash junixsocket-native/crossclang/bin/clang ``` -------------------------------- ### Run junixsocket self-test Source: https://github.com/kohlschutter/junixsocket/blob/main/README.md Execute the self-test JAR to verify platform compatibility. ```bash java -jar junixsocket-selftest-VERSION-jar-with-dependencies.jar ``` -------------------------------- ### Instantiate AFSocketClientConnector Source: https://github.com/kohlschutter/junixsocket/blob/main/junixsocket-jetty/README.md Create a client connector using a specific socket address. ```java ClientConnector clientConnector = AFSocketClientConnector.withSocketAddress(afAddr); ``` ```java AFSocketClientConnector.withSocketAddress(AFUNIXSocketAddress.of(new File("/tmp/socket"))); ``` -------------------------------- ### Verify Platform Support and Capabilities Source: https://context7.com/kohlschutter/junixsocket/llms.txt Check for AF_UNIX support and specific socket capabilities using AFSocketCapability. This ensures the environment supports required features like file descriptor passing or abstract namespaces. ```java import org.newsclub.net.unix.AFUNIXSocket; import org.newsclub.net.unix.AFSocket; import org.newsclub.net.unix.AFSocketCapability; // Check basic AF_UNIX support boolean unixSupported = AFUNIXSocket.isSupported(); System.out.println("AF_UNIX supported: " + unixSupported); // Check specific capabilities System.out.println("Capabilities:"); for (AFSocketCapability cap : AFSocketCapability.values()) { boolean supported = AFSocket.supports(cap); System.out.println(" " + cap + ": " + supported); } // Common capabilities to check: // CAPABILITY_UNIX_DOMAIN - AF_UNIX sockets // CAPABILITY_PEER_CREDENTIALS - getPeerCredentials() support // CAPABILITY_ANCILLARY_MESSAGES - File descriptor passing // CAPABILITY_FILE_DESCRIPTORS - File descriptor I/O // CAPABILITY_ABSTRACT_NAMESPACE - Linux abstract namespace // CAPABILITY_TIPC - AF_TIPC sockets // CAPABILITY_VSOCK - AF_VSOCK sockets // Run the built-in self-test // java -jar junixsocket-selftest-2.10.1-jar-with-dependencies.jar ``` -------------------------------- ### Configure Sonatype snapshot repository Source: https://github.com/kohlschutter/junixsocket/blob/main/README.md Enable the Sonatype snapshot repository in your POM to access snapshot builds. ```xml sonatype.snapshots Sonatype snapshot repository https://oss.sonatype.org/content/repositories/snapshots/ default true ``` -------------------------------- ### List Unix Sockets with ss (Linux) Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/unixsockets.md Use 'ss -x' to list Unix domain sockets on Linux. Add 'p' to show peer processes if UNIX_DIAG is enabled in the kernel. ```bash ss -x ``` ```bash ss -xp ``` -------------------------------- ### Inspect UUID via otool Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/peercreds.md Use the otool command-line utility to inspect the UUID for a binary on macOS. ```bash otool -l | grep uuid ``` -------------------------------- ### Compile C code for the current architecture Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/crosscomp.md Use crossclang to compile a C program for the current architecture. The '-target current' flag automatically detects the host system. ```bash # Compile (and link) for the current architecture, no matter what it is crossclang/bin/clang -o test test.c -target current ``` -------------------------------- ### Implement VSOCK Sockets for Virtual Machine Communication Source: https://context7.com/kohlschutter/junixsocket/llms.txt Use VSOCK for guest-to-host communication. CID 2 represents the host, while values 3 and above are used for guest VMs. ```java import org.newsclub.net.unix.vsock.AFVSOCKSocket; import org.newsclub.net.unix.vsock.AFVSOCKServerSocket; import org.newsclub.net.unix.AFVSOCKSocketAddress; // Check if VSOCK is supported if (AFVSOCKSocket.isSupported()) { System.out.println("VSOCK sockets are supported!"); // VSOCK uses CID (Context ID) and port // CID 2 = host, CID 3+ = guest VMs int cid = 2; // Host CID int port = 9999; // Port number AFVSOCKSocketAddress addr = AFVSOCKSocketAddress.ofPortAndCID(port, cid); // Server (typically on host) try (AFVSOCKServerSocket server = AFVSOCKServerSocket.newInstance()) { server.bind(addr); System.out.println("VSOCK server listening on CID " + cid + ", port " + port); try (AFVSOCKSocket client = server.accept()) { // Handle guest connection } } // Client (typically in guest VM) try (AFVSOCKSocket socket = AFVSOCKSocket.connectTo(addr)) { // Communicate with host } } ``` -------------------------------- ### Implement TIPC Sockets for Cluster Communication Source: https://context7.com/kohlschutter/junixsocket/llms.txt Use TIPC sockets for inter-process communication on Linux. Requires checking support via AFTIPCSocket.isSupported() before binding or connecting. ```java import org.newsclub.net.unix.tipc.AFTIPCSocket; import org.newsclub.net.unix.tipc.AFTIPCServerSocket; import org.newsclub.net.unix.AFTIPCSocketAddress; // Check if TIPC is supported if (AFTIPCSocket.isSupported()) { System.out.println("TIPC sockets are supported!"); // Create TIPC socket address using service type and instance // AFTIPCSocketAddress uses TIPC addressing (type, instance, domain) AFTIPCSocketAddress addr = AFTIPCSocketAddress.ofService( 18888, // Service type 1 // Instance ); // Server try (AFTIPCServerSocket server = AFTIPCServerSocket.newInstance()) { server.bind(addr); System.out.println("TIPC server listening..."); try (AFTIPCSocket client = server.accept()) { // Handle TIPC client connection } } // Client try (AFTIPCSocket socket = AFTIPCSocket.connectTo(addr)) { // Communicate over TIPC } } ``` -------------------------------- ### Build Excluding Native Library Source: https://github.com/kohlschutter/junixsocket/blob/main/BUILDING.md Recommended for most use cases, this command builds all modules except for the native junixsocket library. This is useful if you don't need the native component or are on an incompatible platform. ```bash mvn clean install -rf :junixsocket-common ``` -------------------------------- ### Build junixsocket-common, Skipping junixsocket-native-custom Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/building.md Builds the junixsocket-common module while skipping the junixsocket-native-custom dependency. This is a workaround for issues related to the native-custom module during testing. ```bash mvn clean install -Dnative-custom.skip -rf :junixsocket-common ``` -------------------------------- ### Build junixsocket with GCC as Linker Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/building.md Builds junixsocket while explicitly specifying GCC as the compiler and linker. Use this if clang is unavailable or causing issues. ```bash mvn clean install -Djunixsocket.native.default.linkerName=gcc ``` -------------------------------- ### Build Full Release Version of junixsocket Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/building.md Builds the full release version of junixsocket, including all cross-compile destinations. Requires adherence to separate release instructions. ```bash mvn clean install -Dstrict -Drelease ``` -------------------------------- ### Build junixsocket with SNAPSHOT and Specific Module Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/building.md Builds junixsocket using SNAPSHOT dependencies and specifically targets the junixsocket-native-custom module. This is a workaround for missing native artifact access during SNAPSHOT builds. ```bash mvn clean install -Duse-snapshot -rf :junixsocket-native-custom ``` -------------------------------- ### List Connected Unix Sockets with netstat Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/unixsockets.md Use 'netstat --unix' to display connected Unix domain sockets. ```bash netstat --unix ``` -------------------------------- ### RMI Client using AFUNIXNaming Source: https://context7.com/kohlschutter/junixsocket/llms.txt Connects to an RMI server over Unix domain sockets using AFUNIXNaming. It retrieves the naming instance, looks up the registry, and then calls remote methods on the bound service. ```java import org.newsclub.net.unix.rmi.AFUNIXNaming; import org.newsclub.net.unix.rmi.AFRegistry; import java.io.IOException; import java.rmi.Remote; import java.rmi.RemoteException; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; // Define a remote interface interface Calculator extends Remote { int add(int a, int b) throws RemoteException; int multiply(int a, int b) throws RemoteException; } // Implement the remote interface class CalculatorImpl implements Calculator { public int add(int a, int b) { return a + b; } public int multiply(int a, int b) { return a * b; } } // RMI Client public class RMIClient { public static void main(String[] args) throws Exception { // Get the naming instance AFUNIXNaming naming = AFUNIXNaming.getInstance(); // Look up the registry Registry registry = naming.getRegistry(); // Look up the remote service Calculator calc = (Calculator) registry.lookup("calculator"); // Call remote methods int sum = calc.add(10, 20); int product = calc.multiply(5, 6); System.out.println("10 + 20 = " + sum); System.out.println("5 * 6 = " + product); } } ``` -------------------------------- ### Check Peer Credential Support Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/peercreds.md Verify if the current platform supports peer credentials before attempting to use them. ```java AFUNIXSocket.supports(AFUNIXSocketCapability.CAPABILITY_PEER_CREDENTIALS) ``` -------------------------------- ### Compile C code using default clang Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/crosscomp.md Use crossclang with the default clang compiler for the current architecture. The '-target default' flag uses the system's default clang. ```bash # Compile (and link) using the default clang for the current architecture crossclang/bin/clang -o test test.c -target default ``` -------------------------------- ### Build junixsocket and Skip Tests Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/building.md Builds junixsocket but skips running the tests. This can be useful for faster builds or when tests are known to be problematic. ```bash mvn clean install -DskipTests ``` -------------------------------- ### PostgreSQL Connection via Unix Sockets (FactoryArg) Source: https://context7.com/kohlschutter/junixsocket/llms.txt Connects to PostgreSQL using a JDBC URL and properties that specify the Unix domain socket path via the FactoryArg socket factory. This method is an alternative to the URIScheme approach. ```java import org.newsclub.net.unix.AFUNIXSocketFactory; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.Properties; import java.net.URLEncoder; // Method 2: Using FactoryArg socket factory String url2 = "jdbc:postgresql://localhost/mydb"; Properties props2 = new Properties(); props2.setProperty("socketFactory", "org.newsclub.net.unix.AFUNIXSocketFactory$FactoryArg"); props2.setProperty("socketFactoryArg", socketPath); props2.setProperty("user", "postgres"); try (Connection conn = DriverManager.getConnection(url2, props2)) { System.out.println("Connected via Unix socket!"); } ``` -------------------------------- ### Compile C code for ARMv5 Linux Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/crosscomp.md Use crossclang to compile a C program for ARMv5 Linux. Specify the target architecture and ABI. ```bash # Compile (and link) for ARMv5 Linux crossclang/bin/clang -o test-linuxarmv5 test.c -target armv5tel-unknown-linux-gnueabi ``` -------------------------------- ### Build junixsocket with Ignored Code Quality Checks Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/building.md Builds junixsocket with code quality checks turned off to significantly shorten build times. Use with caution as it may hide potential issues. ```bash mvn clean install -Dignorant ``` -------------------------------- ### Cross-compiling with Release Profile Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/crosscomp.md Cross-compilation is enabled by default when using the release profile (`-Drelease`), unless explicitly disabled with `-Dcross=false`. ```bash mvn clean install -Drelease ``` -------------------------------- ### Run Junixsocket Selftest Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/demo.md Execute the selftest jar to verify junixsocket functionality on the current platform. Ensure the version number in the jar name is correct. ```bash java -jar junixsocket-selftest-X.Y.Z-jar-with-dependencies.jar ``` -------------------------------- ### Unix Domain Socket NIO Server with Selector (Java) Source: https://context7.com/kohlschutter/junixsocket/llms.txt Implement a non-blocking Unix domain socket server using AFUNIXServerSocketChannel and Selector for multiplexing. Handles client connections and echoes received data. ```java import org.newsclub.net.unix.AFUNIXSocketChannel; import org.newsclub.net.unix.AFUNIXServerSocketChannel; import org.newsclub.net.unix.AFUNIXSocketAddress; import org.newsclub.net.unix.AFUNIXSelectorProvider; import java.io.File; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; AFUNIXSocketAddress addr = AFUNIXSocketAddress.of(new File("/tmp/nio.sock")); // Non-blocking server with selector try (AFUNIXServerSocketChannel serverChannel = AFUNIXServerSocketChannel.open()) { serverChannel.bind(addr); serverChannel.configureBlocking(false); Selector selector = AFUNIXSelectorProvider.provider().openSelector(); serverChannel.register(selector, SelectionKey.OP_ACCEPT); while (selector.select() > 0) { for (SelectionKey key : selector.selectedKeys()) { if (key.isAcceptable()) { AFUNIXSocketChannel client = serverChannel.accept(); client.configureBlocking(false); client.register(selector, SelectionKey.OP_READ); } else if (key.isReadable()) { AFUNIXSocketChannel client = (AFUNIXSocketChannel) key.channel(); ByteBuffer buf = ByteBuffer.allocate(256); int read = client.read(buf); if (read > 0) { buf.flip(); client.write(buf); // Echo back } } } selector.selectedKeys().clear(); } } ``` -------------------------------- ### Check File Descriptor Support Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/filedescriptors.md Verify if the current platform supports sending and receiving file descriptors over AF_UNIX sockets using junixsocket. ```java AFSocket.supports(AFSocketCapability.CAPABILITY_FILE_DESCRIPTORS); ``` -------------------------------- ### Compile C code for x86_64 Linux Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/crosscomp.md Use crossclang to compile a C program for x86_64 Linux. Ensure the target architecture and operating system are correctly specified. ```bash # Compile (and link) for x86_64 Linux crossclang/bin/clang -o test-linux64 test.c -target x86_64-pc-linux-gnu ``` -------------------------------- ### Build Excluding Native Library and Java 7 Support Source: https://github.com/kohlschutter/junixsocket/blob/main/BUILDING.md This command builds the project excluding the native library and disabling support for older Java 7 features via Retrolambda. Use this if you are only targeting newer Java versions. ```bash mvn clean install -Dretrolambda=false -rf :junixsocket-common ``` -------------------------------- ### Build junixsocket with Strict Code Quality Checks Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/building.md Builds junixsocket with stricter code quality checks enabled, which may reveal more potential errors. ```bash mvn clean install -Dstrict ``` -------------------------------- ### Receive File Descriptors from AFUNIXSocket Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/filedescriptors.md Configure an AFUNIXSocket to receive ancillary file descriptors and retrieve them after reading data. A reasonable ancillary receive buffer size should be set. ```java AFUNIXSocket socket = ... // set ancillary receive buffer to a reasonable size (disabled by default!) socket.setAncillaryReceiveBufferSize(1024); InputStream in = socket.getInputStream(); // do you regular socket IO here in.read(...) // If there were any file descriptors sent as ancillary messages, check them right after a call to read FileDescriptor[] descriptors = socket.getReceivedFileDescriptors(); if (descriptors != null) { for (FileDescriptor fd : descriptors) { FileInputStream fin = new FileInputStream(fd); // do something with the stream } } ``` -------------------------------- ### PostgreSQL Connection via Unix Sockets (URIScheme) Source: https://context7.com/kohlschutter/junixsocket/llms.txt Connects to PostgreSQL using a JDBC URL that specifies a Unix domain socket path via the URIScheme socket factory. Ensure the socket path is correctly encoded and the properties are set for user, password, and SSL mode. ```java import org.newsclub.net.unix.AFUNIXSocketFactory; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.Properties; import java.net.URLEncoder; // Method 1: Using URIScheme socket factory String socketPath = "/var/run/postgresql/.s.PGSQL.5432"; String encodedPath = URLEncoder.encode("file://" + socketPath, "UTF-8"); String url = "jdbc:postgresql://[" + encodedPath + ":5432/mydb"; Properties props = new Properties(); props.setProperty("socketFactory", "org.newsclub.net.unix.AFUNIXSocketFactory$URIScheme"); props.setProperty("user", "postgres"); props.setProperty("password", "secret"); props.setProperty("sslMode", "disable"); // Not needed for local connections try (Connection conn = DriverManager.getConnection(url, props); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT version()")) { while (rs.next()) { System.out.println("PostgreSQL version: " + rs.getString(1)); } } ``` -------------------------------- ### Create AFUNIXSocketAddress Source: https://context7.com/kohlschutter/junixsocket/llms.txt Generate socket addresses from various sources like files, paths, byte arrays, or URIs to define connection or binding points. ```java import org.newsclub.net.unix.AFUNIXSocketAddress; import java.io.File; import java.nio.file.Path; import java.net.URI; // From a File AFUNIXSocketAddress addr1 = AFUNIXSocketAddress.of(new File("/tmp/my.sock")); // From a Path with an optional port AFUNIXSocketAddress addr2 = AFUNIXSocketAddress.of(Path.of("/var/run/app.sock"), 8080); // From a byte array (for abstract namespace, prefix with zero byte) AFUNIXSocketAddress addr3 = AFUNIXSocketAddress.of(new byte[]{0, 'm', 'y', 's', 'o', 'c', 'k'}); // From a URI AFUNIXSocketAddress addr4 = AFUNIXSocketAddress.of(URI.create("unix:///tmp/my.sock")); // Create a temporary socket address AFUNIXSocketAddress tempAddr = AFUNIXSocketAddress.ofNewTempFile(); // Create address in the abstract namespace (Linux only) AFUNIXSocketAddress abstractAddr = AFUNIXSocketAddress.inAbstractNamespace("my-app-socket"); AFUNIXSocketAddress abstractAddrWithPort = AFUNIXSocketAddress.inAbstractNamespace("my-app", 5000); ``` -------------------------------- ### Send File Descriptors via AFUNIXSocket Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/filedescriptors.md Send one or more FileDescriptors as ancillary messages along with regular data over an AFUNIXSocket. Ensure at least one byte of data is sent to accompany the ancillary messages. ```java AFUNIXSocket socket = ... FileInputStream fin = new FileInputStream(file); socket.setOutboundFileDescriptors(fin.getFD()); // you can also send more than one FD at the same time, just make sure they're all part of the same call to setOutboundFileDescriptors. // Ancillary messages are sent _along_ regular in-band messages, so we have to send something here. os.write("Some message".getBytes("UTF-8")); ``` -------------------------------- ### Check FileDescriptor as Redirect Capability Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/filedescriptors.md Verify if the environment supports using FileDescriptor as a redirect for ProcessBuilder. This check is crucial as the feature is platform-dependent and relies on Java SDK internals. ```java if (AFSocket.supports(AFSocketCapability.CAPABILITY_FD_AS_REDIRECT)) {...} ``` -------------------------------- ### Send FileDescriptor via ProcessBuilder.Redirect Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/filedescriptors.md Pass a FileDescriptor as standard input to a process launched with ProcessBuilder by casting it to ProcessBuilder.Redirect. This functionality requires Java 9+ and is not supported on Windows. ```java FileDescriptor fd = ...; ProcessBuilder pb = ...; pb.redirectInput(FileDescriptorCast.using(fd).as(ProcessBuilder.Redirect.class)); Process p = pb.start(); ``` -------------------------------- ### Compile C code for x86_64 macOS Source: https://github.com/kohlschutter/junixsocket/blob/main/src/site/markdown/crosscomp.md Use crossclang to compile a C program for x86_64 macOS. Specify the target architecture and macOS version. ```bash # Compile (and link) for x86_64 macOS crossclang/bin/clang -o test-mac64 test.c -target x86_64-apple-darwin18.2.0 ```