我在将值传递给recvfrom和sendto函数时遇到问题

时间:2014-05-03 17:12:50

标签: c sockets udp

当编译器达到reliableRecv时,我得到了一个eroor   当编译器达到reliableRecv时,我得到了一个eroor

 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);

和reliableRecv定义如下

 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;
}    

1 个答案:

答案 0 :(得分:0)

我看到两个问题:

  1. 你假装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 *选项之前设计的。

  2. 您将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;
    }