Ben Chuanlong Du's Blog

It is never too late to learn.

Check Whether a File Is a Socket in Golang

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

In [1]:
import "os"
import "io/fs"
import "fmt"
import "log"

Tips and Traps

The bits encoding for file mode might be different for different languages. For example, the encoding in Golang and in Python are differnt. As a matter of fact, even for the same language, different libraries might use different encodings. It is critical to use interfaces provided by the library that you use instead of assuming a specific encoding.

In [2]:
// Check if a file is a socket.
func IsSocket(path string) bool {
	fileInfo, err := os.Stat(path)
	if err != nil {
		log.Fatal("ERROR - ", err)
	}
	return fileInfo.Mode().Type() == fs.ModeSocket
}
In [ ]:
IsSocket("rust.md")
In [ ]:
IsSocket("/home/dclong/.ssh/control/dclong@10.0.0.47:22")
In [ ]:
 

Comments