Ciao ragazzi.
ho scritto un sender UDP che invia file.
Vorrei passargli quando lo eseguo l'indirizzo IP a cui inviare il file e il percorso dove si trova il file.
esempio in linux da shell ./sender 10.0.0.201 /home/myfolfder/pippo.txt
So che si può usare il vettore argv, ho provato a farlo con il mio programma ma ottengo segmentation fault. Se inserissi direttamente nel codice l'ind IP e il percorso, il programma funzionerebbe correttamente
il listato è il seguente:
Grazie
Codice PHP:
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#define PORT 5500
#define BUFFSIZE 4096
#define MIN(_x_,_y_)(((_x_)<(_y_) )? (_x_):(_y_))
#define DEBUG 0
int main (int argc, char* argv){
printf("argc %d", argc);
if (argc != 2) {
fprintf(stderr,"usage: IPdestination path \n");
exit(1);
}
FILE* fin;
int sd; /*socket descriptor*/
struct sockaddr_in dest;
char buf[BUFFSIZE]; /*buffer for socket*/
unsigned long length, file_size, encoded_file_size, chunk_size;
memset((char *)&dest, 0, sizeof(dest));
dest.sin_family = AF_INET;
dest.sin_port = htons(PORT);
dest.sin_addr.s_addr = inet_addr(argv[1]); /*destination's address*/
if ((sd = socket(PF_INET,SOCK_DGRAM,0))<0) {
perror("socket creation");
}
fin = fopen(argv[2],"rb");
if (fin != NULL){
fseek(fin,0, SEEK_END);
file_size = ftell(fin);
#ifdef DEBUG
printf("file_size %ld \n",file_size);
#endif
fseek(fin,0, SEEK_SET);
encoded_file_size = htonl(file_size); /*send dim file*/
if(sendto(sd, &encoded_file_size, sizeof(encoded_file_size), 0, (struct sockaddr*)&dest, sizeof(dest))<0){
perror("send to error");
}
for (length=0; length < file_size; length += chunk_size ){
chunk_size = MIN(BUFFSIZE, file_size-length);
fread(buf, chunk_size,1, fin); /*Check*/
#ifdef DEBUG
printf("chunk_size %ld \n", chunk_size);
printf("length %ld \n", length);
#endif
if (chunk_size != sendto(sd, buf, chunk_size,0,(struct sockaddr*)&dest, sizeof(dest)))
perror("Unable to send data");
}
fclose(fin);
}else{
printf("Unable to open file");
}
if (length == file_size){
printf(" file has been sent successfully \n");
}
close(sd);
}