Question

I am currently trying to write a tftp in C. But i have some difficulties to read the packet that I sent. Here is what I have : The struct that I am sending :

typedef struct {
short type;
short block_num;
char* data;
} data_t;

the function (server's side) wich send the packet :

 if ( s = sendto (serverSocket, data, 512 ,0,
                    (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0 )
                {
                    perror("sendto");
                    exit(1);
                }

For some reason s = 0, I am not sure it is correct.

Client's side :

  char buffer[512 ];
  if ( (n = recv(serverSocket, buffer, 512-1,0)) < 0 )
        {
            perror("recv");
            exit(1);
        }
   data_t * data = malloc (1024);
   data->data = malloc(512);
   create_data(buffer,data)

and the create_data function :

int create_data( char * buffer, data_t* request)

{

data_t * tmp = (data_t*) buffer;
request->type = tmp->type;
request->block_num = tmp->block_num;
strcpy(request->data, tmp->data);
return 0;
}

Unfortunatly it does not work, it seems the issue comes from strcpy in create_data , but I don't know why.

here is the code for serverSocket creation (server's side)

memset( (char *) &serv_addr,0, sizeof(serv_addr) );
serv_addr.sin_family = PF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(SERV_PORT);

/*
* Ouvrir socket UDP
*/
if ((serverSocket = socket(PF_INET, SOCK_DGRAM, 0)) <0)
{
    perror ("erreur socket");
    exit (1);
}
ttl=1;
if (setsockopt(serverSocket, IPPROTO_IP, IP_TTL, &ttl, sizeof(ttl)) <0)
{
    perror ("setsockopt");
    exit (1);
}
if ( bind(serverSocket,(struct sockaddr *) & serv_addr, sizeof(serv_addr) ) < 0 )
{
    perror("servecho: erreur bind\n");
    exit(1);
}

request = malloc(sizeof(request_t));
                    ....
Was it helpful?

Solution

sendto returns number of bytes sent, so if it is returning 0, no bytes have been sent.

In the server part of code, you seem to have a sendto with destination as server address ? (which has INETADDR_ANY as the address). This could be the reason for malfunction. The procedure should be to have the server do a recvfrom first (after bind) and then respond back with sendto, to same address received in recvfrom. Here is a good example for Server and Client.

Received data or data to be sent is binary, you cannot use strcpy, strcpy will stop at the first null byte '\0', you need to use memcpy.

Good practice: While allocating memory data_t * data = malloc (1024);, I recommend you use malloc( sizeof(data_t));

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top