为什么我会遇到“无效论证”?在尝试接受连接时?
在接下来的代码中,当我尝试连接客户端时,服务器显示以下错误:
“参数无效”,我看不到错误。
if((l_sock=socket(AF_INET,SOCK_STREAM,0))!=-1)
{
struct sockaddr_in srv_dir;
srv_dir.sin_family=AF_INET;
srv_dir.sin_port=8500;
srv_dir.sin_addr.s_addr=INADDR_ANY;
if((bind(l_sock,(struct sockaddr *)&srv_dir,sizeof(struct sockaddr_in)))!=-1)
{
if(!(listen(l_sock,5)))
{
signal(SIGINT,cerraje);
int t_sock;
struct sockaddr_in cli_dir;
socklen_t tam;
time_t tstmp;
struct tm * res;
res=(struct tm *)malloc(sizeof(struct tm));
while(!key)
{
if((t_sock=accept(l_sock,(struct sockaddr *)&cli_dir,&tam))!=-1)
{
tstmp=time(&tstmp);
res=gmtime(&tstmp);
send(t_sock,res,sizeof(struct tm),0);
wr_hora(*res,cli_dir.sin_addr);
}
else
perror("Petición no atendida");//The error is printed here.
In the next code, while I try to connect a client the server shows the following error:
"invalid argument", I can't see the error.
if((l_sock=socket(AF_INET,SOCK_STREAM,0))!=-1)
{
struct sockaddr_in srv_dir;
srv_dir.sin_family=AF_INET;
srv_dir.sin_port=8500;
srv_dir.sin_addr.s_addr=INADDR_ANY;
if((bind(l_sock,(struct sockaddr *)&srv_dir,sizeof(struct sockaddr_in)))!=-1)
{
if(!(listen(l_sock,5)))
{
signal(SIGINT,cerraje);
int t_sock;
struct sockaddr_in cli_dir;
socklen_t tam;
time_t tstmp;
struct tm * res;
res=(struct tm *)malloc(sizeof(struct tm));
while(!key)
{
if((t_sock=accept(l_sock,(struct sockaddr *)&cli_dir,&tam))!=-1)
{
tstmp=time(&tstmp);
res=gmtime(&tstmp);
send(t_sock,res,sizeof(struct tm),0);
wr_hora(*res,cli_dir.sin_addr);
}
else
perror("Petición no atendida");//The error is printed here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
阅读有关
accept(2)
的文档:因此,您需要使用
sizeof(cli_dir) 初始化传递给
。您很幸运,套接字库能够捕获您的错误,因为您传递的是未初始化的内存,这会导致未定义的行为。accept
的tam
值Read the documentation on
accept(2)
:So you need to initialize the value of
tam
passed intoaccept
withsizeof(cli_dir)
. You're fortunate that the socket library was able to catch your error, because you're passing in uninitialized memory, which results in undefined behavior.