setsockopt:C 中的错误文件描述符++
我有著名的错误“地址已在使用中”,因为我没有检查绑定函数。
这是我的代码:
memset(&(this->serv_addr), 0, sizeof(this->serv_addr));
this->serv_addr.sin_family = AF_INET;
this->serv_addr.sin_port = htons(port);
this->serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
int yes = 1;
if (setsockopt(sock_fd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int)) == -1) {
perror("setsockopt");
exit(1);
}
但是运行代码我得到了这个: setsockopt:错误的文件描述符
代码是正确的,来自指南 Beejnet。 但为什么我收到错误? 也许代码的位置是错误的?
首先调用 sock_fd 的是函数 w_socket:
int retv;
retv = socket(AF_INET, SOCK_STREAM, 0);
if(retv == -1)
{
std::string err_msg(strerror(errno));
err_msg = "[socket] " + err_msg;
throw err_msg;
}
else
{
int reuse_opt = 1;
setsockopt(this->sock_fd, SOL_SOCKET, SO_REUSEADDR, &reuse_opt, sizeof(int));
return retv;
}
}
默认情况下有 sesockopt 但没有检查。 我已经尝试过,但没有成功。
I have the famous error "address already in use" because I have no check for the bind function.
Here is my code:
memset(&(this->serv_addr), 0, sizeof(this->serv_addr));
this->serv_addr.sin_family = AF_INET;
this->serv_addr.sin_port = htons(port);
this->serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
int yes = 1;
if (setsockopt(sock_fd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int)) == -1) {
perror("setsockopt");
exit(1);
}
But running code I got this:setsockopt: Bad file descriptor
The code is right, from the guide Beejnet.
But why I got the error?
Maybe the position of the code is wrong?
The first the that sock_fd is called is in the function w_socket:
int retv;
retv = socket(AF_INET, SOCK_STREAM, 0);
if(retv == -1)
{
std::string err_msg(strerror(errno));
err_msg = "[socket] " + err_msg;
throw err_msg;
}
else
{
int reuse_opt = 1;
setsockopt(this->sock_fd, SOL_SOCKET, SO_REUSEADDR, &reuse_opt, sizeof(int));
return retv;
}
}
By default there's the sesockopt but no check.
I've tried but it doesn't work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要首先通过
socket
调用创建套接字,例如:(并检查返回值;有关详细信息,请参阅
man 2 socket
)只有这样您才能执行您的
setsockopt
调用。在调用socket
之前,您的sock_fd
变量将包含一个随机值(或 0),而不是套接字文件描述符。更新问题后编辑:
您对
setsockopt
的调用需要使用retv
而不是this->sock_fd
,如下所示在该时间点,this->sock_fd
变量尚未包含调用socket
的结果。You need to first create the socket via the
socket
call, like:(and check the return value; see
man 2 socket
for details)Only then you may do your
setsockopt
call. Before the call tosocket
, yoursock_fd
variable will contain a random value (or 0) instead of a socket file descriptor.Edit after updated question:
Your call to
setsockopt
needs to useretv
instead ofthis->sock_fd
as at that point in time, thethis->sock_fd
variable is not yet containing the result of your call tosocket
.