i am working on c++ server client example using sockets....
whenever i tried to run server 2nd time on the same port it fails !! ok... i know that port is not free and still opened for my previous program but i have used SO_REUSEADDR but still it's not working for 2nd time...
Any one can help me ???
i want to know why SO_REUSEADDR is not working ???
or if its working how could i know it had worked ??
Thanks.

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <iostream>
using namespace std;

#define SERV_TCP_PORT 8001 /* server's port number */
#define MAX_SIZE 80

int main()
{
  int sockfd, newsockfd, clilen;
  struct sockaddr_in cli_addr, serv_addr;
  int port;
  char string[MAX_SIZE];
  
  port = SERV_TCP_PORT;
  
  /* open a TCP socket (an Internet stream socket) */
  if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
     perror("can't open stream socket");
     exit(1);
  }


 // int socket_desc; /* master socket returned by socket() */
  int opt=1;    /* option is to be on/TRUE or off/FALSE */
  int b;
  b = setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,(char *)&opt,sizeof(opt));	
	cout << "B: "<< b << endl;

  	
  /* bind the local address, so that the cliend can send to server */
  memset((char *) &serv_addr, 0, sizeof(serv_addr));
  serv_addr.sin_family = AF_INET;
  serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
  serv_addr.sin_port = htons(port);
  
  if(bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
     perror("can't bind local address-aaaa");
     exit(1);
  }
	
  /* listen to the socket */
  listen(sockfd, 5);

  for(;;) {

     /* wait for a connection from a client; this is an iterative server */
     clilen = sizeof(cli_addr);
     newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
		
     if(newsockfd < 0) {
        perror("can't bind local address");
     }
   
     /* read a message from the client */
     read(newsockfd, string, MAX_SIZE); 
     printf("%s\n", string);
     
     close(newsockfd);
  }     
   return 0;  
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.