sendto():UDP中的错误文件描述符 - IPv6

时间:2012-04-27 15:27:12

标签: c udp ip ipv6 sendto

static void app(const char *address, int port, char *name)
{
  int sock;
  struct addrinfo server;

  sock = init_connection(address,port,&server);
  char buffer[BUF_SIZE];

  write_server(sock, &server, name); /*error is here*/

  /* ..... */   
}

连接功能

static int init_connection(const char *address, int port, struct addrinfo *server)
{
  int sockfd;

  struct addrinfo hints;

  hints.ai_family = AF_UNSPEC; /*ipv4 or ipv6 */
  hints.ai_socktype = SOCK_DGRAM; /* UDP mode */
  hints.ai_flags = 0;
  hints.ai_protocol = IPPROTO_UDP;

  char port_s[BUF_SIZE];
  sprintf(port_s,"%d",port); /* port in char* */

  if((getaddrinfo(address, port_s, &hints, &result)) != 0)
{
    perror("getaddrinfo()");
    exit(EXIT_FAILURE);
}

for (rp = result; rp != NULL; rp = rp->ai_next)
{
    //Creating the socket
    if((sockfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol)) == -1)
    {
        continue;
    }
    else
    {
        break;
    }
}

  return sockfd;
}

sendto(): 问题在于此功能

static void write_server(int sockfd,struct addrinfo *client, char *buffer) /* write to server */
{
    if(sendto(sockfd, buffer, strlen(buffer), 0, client->ai_addr, sizeof (struct addrinfo)) < 0)
      {
        perror("sendto()");
        exit(EXIT_FAILURE);
      }
}

主要:

int main(int argc, char **argv)
{
  if(argc != 3)
  {
    printf("Usage : %s addr_serv port_number\n", argv[0]);
    return EXIT_FAILURE;
  }

  char name[20]="name";
  int port=atoi(argv[2]); 
  app(argv[1], port, name);

  return EXIT_SUCCESS;   
} 

我的write_server函数有问题。 我变成了sendto():无效的参数 有人知道这个问题吗?

谢谢!

2 个答案:

答案 0 :(得分:1)

您尚未在sockfd中为init_connection分配值。您需要至少拨打socket一次。查看getaddrinfo的手册页以获取更多信息:

       /* getaddrinfo() returns a list of address structures.
          Try each address until we successfully bind(2).
          If socket(2) (or bind(2)) fails, we (close the socket
          and) try the next address. */

       for (rp = result; rp != NULL; rp = rp->ai_next) {
           sfd = socket(rp->ai_family, rp->ai_socktype,
                   rp->ai_protocol);
           if (sfd == -1)
               continue;

           if (bind(sfd, rp->ai_addr, rp->ai_addrlen) == 0)
               break;                  /* Success */

           close(sfd);
       }

答案 1 :(得分:-1)

您的sockfd从未初始化且无效。您没有在任何地方建立连接。建立连接时会返回sockfd。