为什么我有“无效参数"?在尝试接受连接时? [英] Why am I having "Invalid argument" while trying to accept connections?

查看:14
本文介绍了为什么我有“无效参数"?在尝试接受连接时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下一个代码中,当我尝试连接客户端时,服务器显示以下错误:

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.

推荐答案

阅读文档 accept(2):

addrlen 参数是一个值结果参数:它最初应该包含 addr 指向的结构的大小;返回时,它将包含返回地址的实际长度(以字节为单位).当 addr 为 NULL 时,不填写任何内容.

The addrlen argument is a value-result argument: it should initially contain the size of the structure pointed to by addr; on return it will contain the actual length (in bytes) of the address returned. When addr is NULL nothing is filled in.

所以你需要用sizeof(cli_dir)初始化tam传入accept的值.您很幸运,套接字库能够捕获您的错误,因为您传入了未初始化的内存,这会导致未定义的行为.

So you need to initialize the value of tam passed into accept with sizeof(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.

这篇关于为什么我有“无效参数"?在尝试接受连接时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆