我是套接字编程的新手。我正在尝试编写一个基本的套接字编程程序。我查找了socket(),bind(),setsockopt()函数和其他函数以及工作代码示例的用法。在setsockopt()函数中,我使用了SO_REUSEPORT选项,但是第一次在给定端口地址上运行程序时它工作正常,但是对于任何后续运行绑定都会失败,除非我已经更改为其他一些端口地址
我的代码示例: -
#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。我是一个初学者,并不太了解上面使用的大多数参数
答案 0 :(得分:3)
我认为这就是你想要做的事情:
const int opt = 1;
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt));