-1

Client sends file name first, and the server makes a file with that name to write data into it.

The file name is cast from command argument, which is in form like 'file.txt'. The problem is that an error occurs every time I cast a file name other than '.txt'.

I'm testing the codes under circumstance with packet loss, with 15% probability. If a loss occurs the whole packet will go away, not leaving any part of it. That's why I thought the file name is lost every time. If the file name packet is not lost, the file would open with a proper name. So I thought it would receive a proper one at least one every 10 times, but it hasn't ever.

//send the file name to the server
byteSent = sendto(sockfd, argv[3], sizeof(argv[3]), 0,
        (struct sockaddr*)&addr, addr_size);

There isn't any other problem with those variables, I guess. It worked as I expected when packet loss not assumed. I changed the 3rd argument from strlen(argv[3]) + 1, but nothing had changed from it.

if((byteRcvd = recvfrom(sockfd, buf, sizeof(buf), 0,
    (struct sockaddr*)&addr, &addr_size)) < 0)
    exit(1);
byteRcvd = BUFFER_SIZE;

fp = open(buf, O_RDWR | O_CREAT, 0644);
    //printf("file \"%s\" is opened\n", buf);

Can I solve this problem by modifying the codes?

Yeongchan Jeon
  • 499
  • 3
  • 18
  • 1
    No. You need to **entirely** redesign this based on a sound understanding of networking. Among the most obvious points you have overlooked is that UDP can deliver packets out of order, so you could get data before the filename, and that writing to an arbitrary, unchecked filename provided over an unsecured network connection is absurdly unsafe. – Chris Stratton Nov 22 '15 at 18:12
  • Also, you are sending a *pointer* to the characters. This pointer has no meaning in the receiving process. – Martin R Nov 22 '15 at 18:14

1 Answers1

0

As Chris Stratton wrote in comment - most of your code should be changed. The design of your file transfer protocol is naive. There are a lot of potential problems

  • UDP may deliver packet in different order than sender sent them.
  • Server cannot recognize what datagram contains file data and what datagram contains filename.
  • Server cannot recognize where is the file end. But may be you need to transfer only small files that fit to one datagram.
  • The server gives possibility to overwrite ANY file without any client authentication.
  • Server does not recognize data coming from different clients.

And there is a minor problem that you probably originally asked about:

byteSent = sendto(sockfd, argv[3], sizeof(argv[3]), 0, ...

argv[3] is char* and `sizeof(char*) is 4 or 8 bytes. Should be probably

byteSent = sendto(sockfd, argv[3], strlen(argv[3]) + 1, 0, ...

Warning: do not test in environment where somebody else can connect to the server machine.

Zaboj Campula
  • 3,155
  • 3
  • 24
  • 42