Socket Programming C++ setsockopt()

Ronit picture Ronit · Jan 15, 2018 · Viewed 7.1k times · Source

I am new to socket programming. I am trying to write a basic socket programming program. I looked up the usages of socket(), bind() , setsockopt() functions and the others along with working code samples. In the setsockopt() function , I had used the SO_REUSEPORT option, however first time when I run the program on a given port address it works fine, however for any subsequent runs binding fails unless I have changed to some other port address

My code sample :-

#include<iostream>
#include<cstdio>
#include<sys/socket.h>
#include<sys/types.h>
#include <netinet/in.h>
#include<unistd.h>
#include<cstdlib>
#include<cstring>
using namespace std;

int main(){

    int opt=1;
    socklen_t optlen=sizeof(opt);
    char buffer[1024] = {0};
    int sock=socket(AF_UNIX,SOCK_STREAM,0);
    if(sock==-1)
    {
    cout<<"Socket Creation not successful"<<endl;
    exit(1);
    }
    cout<<"Socket Created"<<endl;
    setsockopt(sock,SOL_SOCKET,SO_REUSEADDR|SO_REUSEPORT,&opt,optlen);
    struct sockaddr_in address;
    address.sin_family = AF_UNIX;
    address.sin_addr.s_addr = htonl(INADDR_ANY);
    address.sin_port = htons(9091);

    int addrlen = sizeof(address);
    int x=bind(sock,(struct sockaddr *)&address,
                            sizeof(address));
    if(x==-1)
    {
            cout<<"Binding Unsuccessful"<<endl;
            exit(1);
    }
    cout<<"Binding successful"<<endl;

/*

     if(x<0)
//      {
//      perror("Bind failed");
//      exit(EXIT_FAILURE);
//      }
    int y=listen(sock,5);
    int neww= accept(sock,(struct sockaddr *)&address, 
                   (socklen_t*)&addrlen);
    //int val=read(neww 
 cout<<sock<<endl;
 cout<<x<<endl;
cout<<y<<endl;
cout<<neww<<endl;

cout<<"Haha";
int valread = read (neww , buffer, 1024);
puts(buffer);
send(neww,buffer,strlen(buffer),0);

*/

int c=close(sock);
cout<<c<<endl;
}

P.S. I am quite a beginner and do not know much about most of the parameters used above

Answer

Jeremy Friesner picture Jeremy Friesner · Jan 15, 2018

I think this is what you want to do:

  const int opt = 1;
  setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt));