Tutorial :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.


There is mktemp program which is available as part of GNU coreutils. See it's manpage for details.

Typical usage is as simple as this:

TEMPDIR=$(mktemp -d)  echo $TEMPDIR  touch $TEMPDIR/yourfile.txt  

(As noted in other answer it is only safe to create a directory.)


You didn't specify the language you are using, but assuming it is a C/C++ dialect (or some other language with access to the C runtime library), you could use the tmpnam function.

There are some issues with tmpnam, the most serious of which is probably that the temporary file name you get back isn't actually "locked" until you use it to create a file, so theoretically some other process could create the file out from under you. You also have to make absolutely sure the buffer you pass tmpnam has enough space to hold the longest path your OS can support.

These days it is recommended that you call tmpfile instead. This will create the file for you in one (hopefully atomic) operation, and give you back a file handle. Another nice benefit is that the file is deleted for you automatically when you close it. No muss, no fuss.


Play with /dev/random.

A quick search on google gave me this hit:

< /dev/urandom tr -dc A-Za-z0-9 | head -c8

If you would like to do the same in C, just open /dev/random and convert it into a string (ignore non valid chars).

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »