直接从/ dev / log Unix Domain Socket读取数据

我的项目旨在直接从Java中的/dev/log UNIX域套接字读取日志消息。 目前我正在使用junixsocket 。 下面是从unix套接字读取的客户端示例代码。

 import java.io.File; import java.io.IOException; import java.io.InputStream; import org.newsclub.net.unix.AFUNIXSocket; import org.newsclub.net.unix.AFUNIXSocketAddress; import org.newsclub.net.unix.AFUNIXSocketException; public class SimpleTestClient { public static void main(String[] args) throws IOException { final File socketFile = new File("/dev/log"); AFUNIXSocket sock = AFUNIXSocket.newInstance(); try { sock.connect(new AFUNIXSocketAddress(socketFile)); } catch (AFUNIXSocketException e) { System.out.println("Cannot connect to server. Have you started it?\n"); System.out.flush(); throw e; } System.out.println("Connected"); InputStream is = sock.getInputStream(); byte[] buf = new byte[8192]; int read = is.read(buf); System.out.println("Server says: " + new String(buf, 0, read)); is.close(); sock.close(); System.out.println("End of communication."); } } 

上面提到的代码无法连接到/dev/log 。 它引发了一个例外:

Cannot connect to server. Have you started it? Exception in thread "main" org.newsclub.net.unix.AFUNIXSocketException: Protocol wrong type for socket (socket: /dev/log) at org.newsclub.net.unix.NativeUnixSocket.connect(Native Method) at org.newsclub.net.unix.AFUNIXSocketImpl.connect(AFUNIXSocketImpl.java:125) at org.newsclub.net.unix.AFUNIXSocket.connect(AFUNIXSocket.java:97) at org.newsclub.net.unix.AFUNIXSocket.connect(AFUNIXSocket.java:87) at SimpleTestClient.main(SimpleTestClient.java:40)

我无法弄清楚如何解决这个问题。 任何帮助都会很明显。

由于您无法连接到日志跟踪中提到的现有服务器套接字,因此您没有将所提到的文件绑定到一个,因此请尝试创建AF_UNIX服务器套接字然后连接到它。

它可以在一个单独的类中完成:

 public class DevLogServer { public static void main(String[] args) throws IOException { final File socketFile = new File("/dev/log"); AFUNIXServerSocket server = AFUNIXServerSocket.newInstance(); try { server.bind(new AFUNIXSocketAddress(socketFile)); } catch (Exception e) { throw e; } } } 

根据@Ankit评论编辑:

您可能还需要确保在终端窗口中通过runnig below命令停止syslod守护程序:

 sudo service syslog stop 

您可能需要对/ dev目录具有宏写入权限。

您是否使用root权限启动应用程序?