sendto错误:参数无效

时间:2015-08-23 12:16:47

标签: c++ linux sockets

我在socket

中使用sendto()函数时遇到了麻烦
int main(int argc, const char * argv[]) {

    int acceptFd;
    struct sockaddr_in servaddr, cliaddr;
    char recieveBuf[512];
    char sendBuf[512];
    socklen_t cliLen;

    if(-1 == (acceptFd = socket(AF_INET,SOCK_DGRAM,0))) perror("socket() failed.\n");
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(6789);
    if(-1==bind(acceptFd,(struct sockaddr*)&servaddr,sizeof(servaddr))) perror("bind() failed.\n");


    bzero(&cliaddr, sizeof(cliaddr));

    while(1){


        if(recvfrom(acceptFd, recieveBuf, 512, 0, (struct sockaddr*) &cliaddr, &cliLen) == -1) {
            perror("recvfrom() failed");
            continue;
        }

        strcpy(sendBuf,"recieved\n");
        printf("%s\n",sendBuf);
        if(-1 == sendto(acceptFd,sendBuf, 512,0,(struct sockaddr*)&cliaddr,cliLen)){
            perror("sendto() failed");
            continue;
        }
    }
}

recvfrom()工作正常,但每次调用sendto()时,错误处理都会打印出来:sendto() failed: Invalid argument

发送程序在这里:

#include "test.AcceptMessage.pb.h"
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>

int main(int argc, const char * argv[]) {



    int sendSocket;
    struct sockaddr_in cliaddr;
    char buf[512];
    if(-1 == (sendSocket = socket(AF_INET,SOCK_DGRAM,0))) perror("socket() failed.\n");
    bzero(&cliaddr, sizeof(cliaddr));
    cliaddr.sin_family = AF_INET;
    cliaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
    cliaddr.sin_port = htons(6789);

    sendto(sendSocket,buf, 512,0,(
            struct sockaddr*)&cliaddr, sizeof(cliaddr));



    recvfrom(sendSocket,buf,512,0, nullptr, nullptr);
    printf("%s\n",buf);





    return 0;
}

这个代码有什么问题?

2 个答案:

答案 0 :(得分:3)

来自man recvfrom

  

在通话之前,应该将[addrlen]初始化为大小          与src_addr相关联的缓冲区。

因此,请使用以下内容初始化cliLen变量:

socklen_t cliLen = sizeof(cliaddr);

答案 1 :(得分:0)

您根本没有理由在这里使用recvfrom()sendto()。它是一个连接的插座。只需使用send()recv().

即可