Home > Software design >  How random is a linux socket file description assignment?
How random is a linux socket file description assignment?

Time:10-19

I am writing a C# app to communicate with my wireless card using netlink protocol (via libnl library), in Linux.

Basically I am mimicking iw's functionality. At this initial state, I want to make sure the initial ported calls results are the same as when debugging the real linux app.

They are - except for the result I get for acquiring a socket file descriptor, using nl_socket_get_fd. Debugging the app always return a file descriptor valued 3, while my c# app extern call to nl_socket_get_fd always return 26 (even after system boots).

I remember from a while back I tried to do the same - but mimicking iwlist instead (before noticing it is now deprecated). Debugging also always returned 3 (eventually calling libc's socket function), while debugging my C# port always returned 19.

Socket's man page says

socket() creates an endpoint for communication and returns a file descriptor that refers to that endpoint. The file descriptor returned by a successful call will be the lowest-numbered file descriptor not currently open for the process.

I understand a file descriptor is "randomly" assigned, just found it suspicious that it always return the same number when running in this or that way.

Is this something to worry about ? Does this indicate my ported code is already not working as expected and moving on will end up creating unexpected results ?

CodePudding user response:

The documentation says:

The file descriptor returned by a successful call will be the lowest-numbered file descriptor not currently open for the process.

So if your process has open file descriptors 0, 1, and 2, but not 3, it will return 3.

If your process has open file descriptors 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, and 25, but not 26, it will return 26.

This is how file descriptors are usually assigned in Linux.

  • Related