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*/

  /* ..... */   
}

The connection function

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() : The problem is in this function

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

main :

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

I have a problem with the write_server function. I become sendto() : Invalid argument Does anybody have an idea of the problem ?

Thank you !

user1361431
  • 11
  • 1
  • 3

2 Answers2

1

You have not assigned a value to sockfd in init_connection. You need to call socket at least once. Check the man page of getaddrinfo for more information:

       /* 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);
       }
user1202136
  • 11,171
  • 4
  • 41
  • 62
-1

Your sockfd is never initialised and is not valid. You are not establishing the connection anywhere. The sockfd is returned when you establish the connection.

Drona
  • 6,886
  • 1
  • 29
  • 35