当编译器达到可靠的Recv时,我得到一个错误
  当编译器达到可靠的Recv时,我得到一个错误

 int rvsock;

    rvsock = socket(AF_INET,SOCK_DGRAM,0);
struct sockaddr_in saddr;
struct sockaddr_in caddr;

if (rvsock < 0){
    perror("Failed to create the socket!!");
    exit(1);
}

//we mark the memory pointed by saddr with 0
memset(&saddr,0,sizeof(saddr) );

saddr.sin_family = AF_INET;
saddr.sin_addr.s_addr = INADDR_ANY;
saddr.sin_port = htons(port);

err = bind(rvsock, (struct sockaddr*)&saddr,sizeof(struct sockaddr_in));
if(err < 0){
    perror("Failed to bind");
    exit(1);
}

unsigned int len;
len = sizeof(struct sockaddr_in);

reliableRecv(rvsock,filename,1024,(struct sockaddr*)&caddr,(size_t *)&len);


可靠的Recv是这样定义的

 int reliableRecv(int sockfd,void* buffer,size_t bufferlen,struct sockaddr      *src_addr,size_t *srclen)
{
    int n=recvfrom(sockfd,buffer,bufferlen,0,src_addr,&srclen);
    return n;
}

最佳答案

我看到两个问题:


您假设unsigned longsize_t,不一定准确:



unsigned int len;
len = sizeof(struct sockaddr_in);

reliableRecv(rvsock,filename,1024,(struct sockaddr*)&caddr,(size_t *)&len);




您应该使用:

size_t len = sizeof(struct sockaddr_in);
int nbytes = reliableRecv(rvsock, filename, 1024, (struct sockaddr *)&caddr, &len);


通常,应避免将除void *(或各种char *类型之一)以外的指针转换为其他指针类型。但是,struct sockaddr *强制转换是必需的,并且是“无害的”,即使从大多数角度来看,它也是不可取的。套接字接口是在void *选项之前设计的。
您将size_t **传递给需要size_t *的函数:



int reliableRecv(int sockfd, void *buffer, size_t bufferlen, struct sockaddr *src_addr, size_t *srclen)
{
    int n=recvfrom(sockfd,buffer,bufferlen,0,src_addr,&srclen);
    return n;
}




您应该使用:

int reliableRecv(int sockfd, void *buffer, size_t bufferlen,
                 struct sockaddr *src_addr, size_t *srclen)
{
    int n = recvfrom(sockfd, buffer, bufferlen, 0, src_addr, srclen);
    return n;
}

关于c - 我在将值传递给c中的recvfrom和sendto函数时遇到问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23447484/

10-09 06:59