Jichao Jichao - 8 months ago 57
C Question

How to generate random file name for socket under Linux?

I want to make a small program which use local namespace socket and I will need to use temporary file name as address of the socket.

So how to generate random file name under Linux?

+ I'm using the C programming language under Debian Linux.

+ Acoording to the GNU C Library Reference,tmpname is not safe.But the safe ones tmpfile and mkstemp create and open the generated file.Is there any safe and non-create-open to this.In other words, the function should forbidden any other request to create the generated file name under specific directory.



If you're doing this in C, use mkdtemp to create a directory, and put your socket inside this directory.

Other functions such as tmpnam or mktemp are insecure; since they don't create and open the temp file for you, it's easy to be vulnerable to following a pre-existing symlink (placed by an attacker who guessed your temp filename) to some important file (like /etc/passwd), overwriting it.

Note that there's no way to 'lock' a path - all you can do is create something there. If you need to put a socket there eventually, using a directory as a placeholder is your best bet.