send_to在udp

时间:2018-04-01 13:55:40

标签: sockets networking server udp sendto

我正在创建一个简单的文件传输应用程序,但是当我尝试从服务器端发送到客户端时,send_to正在返回EINVAL,而send_to和recv_from在客户端都正常工作。 port_number,portno,hostname作为参数传递。

设置服务器的代码:

portno=port_number;

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
      error("ERROR opening socket");


    optval = 1;

    setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
         (const void *)&optval , sizeof(int));


    bzero((char *) &serveraddr, sizeof(serveraddr));
    serveraddr.sin_family = AF_INET;
    serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
    serveraddr.sin_port = htons((unsigned short)portno);


    if (bind(sockfd, (struct sockaddr *) &serveraddr,
       sizeof(serveraddr)) < 0)
      error("ERROR on binding");
      //getsockname(sockfd, (struct sockaddr *)&clientaddr, &clientlen);
      cout<<"server port no"<<serveraddr.sin_port<<endl;
    clientlen = sizeof(clientaddr);

设置客户端的代码:     hostname = name;     portno = port;

/* socket: create the socket */
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0)
 error("ERROR opening socket");



/* gethostbyname: get the server's DNS entry */
server = gethostbyname(hostname);
if (server == NULL)
{
  fprintf(stderr,"ERROR, no such host as %s\n", hostname);
  exit(-1);
}

/* build the server's Internet address */
memset((char *) &serveraddr,0, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serveraddr.sin_addr.s_addr, server->h_length);
serveraddr.sin_port = htons(portno);
serverlen = sizeof(serveraddr);
struct timeval tv;

tv.tv_sec = 1;                       // TIMEOUT IN SECONDS
tv.tv_usec = 0;                      // DEFAULT
if(setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0)
  printf("Cannot Set SO_RCVTIMEO for socket\n");

失败的命令:

  if(sendto (sockfd, ack, strlen(ack), 0,(struct sockaddr*) 
  &clientaddr,sizeof(clientaddr) < 0)
       error("ERROR in sending hello_ACK");

其中clientadddr被声明为struct sockaddr_in

1 个答案:

答案 0 :(得分:1)

由于参数无效而生成EINVAL错误。因此,您应该像对serveraddr那样初始化clientaddr,或者如果您之前收到HELLO消息/或者来自客户端的任何其他消息,您可以将clientaddr作为参数传递给该recvFrom调用。

recvfrom(socketFileDescriptor, buffer, bufferSize,0,(struct sockaddr *) &clientaddr, &clientlen))

如果你用C语言编写,那么clientlen是sizeof(clientaddr)