1

Are C socket descriptor returned by socket() function unique ? I called this from two programs simultaneously and i got the same output

(socDes = socket(PF_INET, SOCK_MRP, 0)
printf("%d",socDes);

According to its man page, socket() returns a file descriptor for New socket

if two programs have same socket, how the received packets gets transferred to different process ? Any elaboration will be helpful.

mchouhan_google
  • 1,775
  • 1
  • 20
  • 28
  • What you mean the same socket? because the file descriptors are the same numbers? – Iharob Al Asimi Jan 19 '15 at 18:36
  • 1
    file/socket descriptors are basically an array entry somewhere within the processes' memory space. two processes might both have a socket/file desc that's #42 in each, but those are two entries in two separate arrays and otherwise have no relationship to each other. – Marc B Jan 19 '15 at 18:37

2 Answers2

2

Socket descriptors are file system handles, and should be unique to your process for the duration of it's session. But if you end and re-run, you may very well receive the same value.

Keep in mind, each process has it's own list of file system handles. So file descriptor 3 in process 10 can be very different from file descriptor 3 in process 20.

user590028
  • 11,364
  • 3
  • 40
  • 57
  • so that means if i create multiple sockets, they refer to same file ? – mchouhan_google Jan 22 '15 at 09:15
  • No. Each socket is a unique end point within the same process. Processes do not see each others descriptors UNLESS one is a fork()'ed child, and the parent decides to allow it to be visible to the child. – user590028 Jan 23 '15 at 00:28
0

A file descriptor is a process resource. Every program loaded in your system has it's own, independent set of file descriptors. That's why STDOUT/STDIN correspond to FD 1/2 (or is it 0/1?). In practice file descriptors are numeric identifiers to a resource held by the operating system, they just happen to be printable as integers (there's no guarantee about that on all systems, what you're seeing is an implementation detail). In the operating system your FD 1,2,3,etc correspond to different resources than in another process.

Since each process has its own pool of resources it follows that file descriptors would be in separate pools. They just happen to have the same ID because of how those IDs are allocated by the OS!

xrl
  • 2,155
  • 5
  • 26
  • 40