Question

This might look like a stupid question, but I had nothing better to do at home. Been working on a project. I wrote this code, but could not understand the output. Can someone please explain-

int MasterSocket[3];
int i = 0;
for(i=0; i<3; i++)
{
    MasterSocket[i] = socket(AF_INET , SOCK_STREAM , 0);
}

for(i=0; i<3; i++)
{
    printf("\n%d---\n", MasterSocket[i]);
}

OUTPUT-

ansh@daweed69-laptop:~/Ubuntu One/workspace/multiConnectionSockets/Debug$ ./multiConnectionSockets 

3---

4---

5---

[Update from comments:]

Why did the descriptor outputs have to start from 3? 0, 1 and 2 are predefined!?!?

Was it helpful?

Solution

What do you expect this code to do? If you read the documentation for the socket() function, it says:

SYNOPSIS
       #include <sys/types.h>          /* See NOTES */
       #include <sys/socket.h>

       int socket(int domain, int type, int protocol);
RETURN VALUE  
       On  success,  a  file  descriptor  for  the new socket is returned.  On
       error, -1 is returned, and errno is set appropriately.

This tells you that socket() returns in int and describes it as a "file descriptor" -- which is simply something the operating system uses to refer to an open file or file-like resource. So when you run:

s = socket()

You set s to some integer value that, when used in things like the write() or read() system calls, refers to an open network connection. To understand what sockets are and how to use them, you should read one of the many results you'll find if you search for "socket programming examples".

OTHER TIPS

The socket() system call returns a file descriptor. On UNIX systems that will be an integer. What I don't understand is how you're getting the "3" file descriptor twice. The following code compiles and does NOT get a duplicate file descriptor:

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>

void main() {
  int MasterSocket[3];
  int i = 0;
  for(i=0; i<4; i++)
  {
    MasterSocket[i] = socket(AF_INET , SOCK_STREAM , 0);
  }

  for(i=0; i<4; i++)
  {
    printf("\n%d---\n", MasterSocket[i]);
  }
}

Better check your work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top