0

I can create a socket locally using:

$ python -c "import socket as s; sock = s.socket(s.AF_UNIX); sock.bind('/mnt/somesocket')"

I can check that the file is a socket at the command-line via the following:

$ test foo.txt
$ echo $?
1
$ test -S somesocket
$ echo $?
0

How can I check if the file is a socket using Scala?

1 Answer 1

1

There are multiple options available, but none is perfect...

test will call S_ISSOCK macro as you can see from the code here:

struct stat stat_buf;
...
S_ISSOCK (stat_buf.st_mode)

The macro itself is very simple - just checks if certain bits are set via bitmasks. Relevant code from here:

#define S_IFMT  00170000
...
#define S_IFSOCK 0140000
...
#define S_ISSOCK(m)     (((m) & S_IFMT) == S_IFSOCK)

Thus if you would have a stat structure with st_mode value you would be all set. However, that part is tricky.

Java NIO provides some POSIX support with Files and BasicFileAttributes classes. But it does not expose file mode or any test methods for sockets. If you don't use various types of files you might be ok using isOther:

boolean isOther()

Tells whether the file is something other than a regular file, directory, or symbolic link.

Otherwise you can try JNI / JNA implementations:

https://github.com/SerCeMan/jnr-fuse/blob/master/src/main/java/ru/serce/jnrfuse/struct/FileStat.java

Is there a Java library of Unix functions?

Finally, the simplest but slowest solution is to call a process (shell) from Scala.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.