1
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() : Invalid argument 有人知道这个问题吗?

谢谢 !

4

2 回答 2

1

您尚未为sockfdin分配值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);
       }
于 2012-04-27T15:28:56.757 回答
-1

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

于 2012-04-27T16:17:38.597 回答