简体   繁体   English

套接字编程C ++ setsockopt()

[英]Socket Programming C++ setsockopt()

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. 我查看了socket(),bind(),setsockopt()函数以及其他函数以及工作代码示例的用法。 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 在setsockopt()函数中,我使用了SO_REUSEPORT选项,但是,当我第一次在给定的端口地址上运行程序时,它可以正常工作,但是对于任何后续运行,绑定都将失败,除非我更改为其他端口地址

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;
}

PS I am quite a beginner and do not know much about most of the parameters used above PS我是一个初学者,对上面使用的大多数参数不太了解

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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM