Thread: when to close a socket

  1. #1
    Registered User
    Join Date
    Oct 2003
    Posts
    17

    when to close a socket

    I don't know where I have to put my close():

    my code is like this:

    Code:
    #define SOCKET_ERROR        -1
    #define STRGLEN 100  /* message string length */
    const int APORT = 1234;  /* port number */
    
    
    /*	Function main */
    main(){
    	int fromlen;
    	char hostname[64]; /* local machine hostname */
    	struct hostent *hp; /* gethostbyname return ptr */
    	register int s; /* socket descriptor, or -1 if error */
    	register int ns; /* created new socket for accept */
    	struct sockaddr_in  sin; /* socket structure */
    	struct sockaddr_in fsin; /* socket str. for accept*/
    	int p1;
    
    	
    	/* first need to know our hostname. */
    	gethostname(hostname, sizeof(hostname));
    	
    	/* Next look up the network address of our host.*/
    	if((hp = gethostbyname(hostname)) == NULL){ 
    		fprintf(stderr, "%s: unknown host\n", hostname);
    		exit(-1); 
    	}
    	
    	/* create socket in Internet domain(AF_INET), that is 
    	connection oriented (SOCK_STREAM) rather than
    	connectionless (SOCK_DGRAM),
    	arg3=0 for default TCP/IP protocol*/
    	if(( s = socket(AF_INET, SOCK_STREAM, 0) ) < 0){ 
    		perror("server: socket"); 
    		exit(-1); 
    	}
    	
    	/* Create the address to connecting to. We use port
    	APORT but put it into network byte order.
    	Also we use bcopy to copy the network number. */
    	bzero(&sin, sizeof(sin));
    	sin.sin_family = AF_INET;  /* IP protocol */
    	/* sin.sin_addr.s_addr = INADDR_ANY;*/
    	sin.sin_port = htons(APORT);
    	bcopy(hp->h_addr, &sin.sin_addr, hp->h_length);
    	
    	/* Try to bind(address and port no.)to socket s */
    	if(bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0){ 
    		perror("server: bind"); 
    		exit(-1); 
    	}
    	
    	/* server ready, listen on socket s max 2 requests queued*/
    	if(listen(s, 2) < 0) {
    		perror("server: listen"); 
    		exit(-1); 
    	}
    
       /* Accept connections then fork ns (new socket) that
       will be connected to the client. fsin will contain
       the IP address of the client. */
    	bzero(&fsin, sizeof(fsin));
    	fromlen = sizeof(fsin);
    	if((ns = accept(s, (struct sockaddr *)&fsin, &fromlen))<0){
    		perror("server: accept"); 
    		exit(-1);
    	}
    
    	if((p1 = fork()) > 0){
    		server(ns);
    	}
    	else{	/* child */
    		server(ns);
    	}
    	
    }
    do I put my close(s) in the if, else, or elsewhere?

  2. #2
    root
    Join Date
    Sep 2003
    Posts
    232
    Where's your loop? Assuming this is a server that listens for connections and then forks a new process for the actual client communication, you need logic like so:
    Code:
    /* Open a socket to listen with */
    while (1) {
            /* Accept a connection */
            switch (fork()) {
            case -1:
                    /* Error */
                    break;
            case 0:
                    /* Child closes the listening socket */
                    /* Child processes the request */
                    break;
            }
            /* Parent closes the connection */
            /* Parent cleans up zombies */
    }
    The information given in this message is known to work on FreeBSD 4.8 STABLE.
    *The above statement is false if I was too lazy to test it.*
    Please take note that I am not a technical writer, nor do I care to become one.
    If someone finds a mistake, gleaming error or typo, do me a favor...bite me.
    Don't assume that I'm ever entirely serious or entirely joking.

  3. #3
    Registered User
    Join Date
    Oct 2003
    Posts
    17
    I don't understand several things

    1)what is the loop for? and how do you get out of this loop when you write while(1)?

    2)
    /* Child closes the listening socket */
    /* Child processes the request */
    Shouldn't the child close the socket after it processes the request? (my request include some send/recv)

    3)When I have listen(s, 2), do I have to make 2 fork() (or more) or is one enough?

    4)
    /* Parent closes the connection */
    What's the difference between closing the listening socket and closing the connection? Is "s" the connection and "ns" the listening socket in my code?

    5)
    /* Parent cleans up zombies */
    How do you do that?

  4. #4
    Registered User
    Join Date
    Oct 2003
    Posts
    12
    s is the listening socket
    ns is a new socket created by accept
    when a connnection is accepted you need to fork to handle that connection (ns) but keep looping to accept future connections. Only one fork statement is required since in a loop it should be called each time accept returns a new socket.

  5. #5
    Registered User
    Join Date
    Oct 2003
    Posts
    17
    do I have to put a particular condition in the loop or is "while(1)" just enough?

    and I just don't understand why I have to close the listening socket "s" before the accepted socket "ns". It doesn't seem logical to me
    Last edited by Wisefool; 11-01-2003 at 04:37 PM.

  6. #6
    Registered User
    Join Date
    Oct 2003
    Posts
    17
    if I've understood, I should do this, right?

    Code:
    while(1){ 
          if((child = fork()) == 0){   /* child process */ 
             close(s);   /* close s because this socket was copied with the fork */ 
             server(ns);   /* exchange data with the client */ 
             close(ns);   /* once the childs process is done, close the socket */ 
          } 
       } 
        
       /* use close() to terminate the 
       connection, since we're done with both sides */ 
       close(s);

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. socket programming question, closing sockets...
    By ursula in forum Networking/Device Communication
    Replies: 2
    Last Post: 05-31-2009, 05:17 PM
  2. problem closing socket
    By Wisefool in forum Networking/Device Communication
    Replies: 2
    Last Post: 10-29-2003, 12:19 PM
  3. problem closing a socket
    By Wisefool in forum C Programming
    Replies: 1
    Last Post: 10-28-2003, 01:38 PM
  4. socket newbie, losing a few chars from server to client
    By registering in forum Linux Programming
    Replies: 2
    Last Post: 06-07-2003, 11:48 AM
  5. Ghost in the CD Drive
    By Natase in forum A Brief History of Cprogramming.com
    Replies: 17
    Last Post: 10-12-2001, 05:38 PM