Justin Homes
Justin Homes

Reputation: 3799

how to send files in chunk using socket c/C++?

i have been trying to find how to send a file in chunks in C or C++ i looked at some examples in here did not find good example. i am very new to sockect programming in C/C++

http://beej.us/guide/bgnet/html/single/bgnet.html

any ideas how i need to send files in chunk between client and server? client requesting the file, server sending it back.

i found this for send but not sure about receiving it.

#include <sys/types.h>
#include <sys/socket.h>

int sendall(int s, char *buf, int *len)
{
    int total = 0;        // how many bytes we've sent
    int bytesleft = *len; // how many we have left to send
    int n;

    while(total < *len) {
        n = send(s, buf+total, bytesleft, 0);
        if (n == -1) { break; }
        total += n;
        bytesleft -= n;
    }

    *len = total; // return number actually sent here

    return n==-1?-1:0; // return -1 on failure, 0 on success
}

Upvotes: 3

Views: 9954

Answers (2)

rockdaboot
rockdaboot

Reputation: 736

Take a look at TCP_CORK (man 7 tcp). But really, except you want to become a socket/network programming expert, use a library ! Just think of your next problem: data encryption (e.g. HTTPS/SSL). Libraries care for the gory details...

Upvotes: 0

Umer Farooq
Umer Farooq

Reputation: 7486

I just wrote this code for receiving files in Client using linux sockets in C.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <fcntl.h>


#define PORT 4118

#define MaxBufferLength 1024 // set the size of data you want to recieve from Server


int main()
{
    int sockFd, bytesRead= 1, bytesSent;

    char buffer[MaxBufferLength];

    struct sockaddr_in server, client;


    server.sin_port= htons(PORT);
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr("127.0.0.1");

    sockFd = socket(AF_INET, SOCK_STREAM, 0);


    if(sockFd < 0)
        printf("Unable to open socket\n");

    int connectionSocket = connect(sockFd, (struct sockaddr *) &server, sizeof(struct sockaddr) );

    if(connectionSocket < 0)
        perror("connection not established\n");


    int fd = open("helloworlds.txt",O_CREAT | O_WRONLY,S_IRUSR | S_IWUSR);  

    if(fd == -1)
        perror("couldn't openf iel");

    while(bytesRead > 0)
    {           

        bytesRead = recv(sockFd, buffer, MaxBufferLength, 0);

        if(bytesRead == 0)
        {

            break;
        }

        printf("bytes read %d\n", bytesRead);

        printf("receivnig data\n");

        bytesSent = write(fd, buffer, bytesRead);


        printf("bytes written %d\n", bytesSent);

        if(bytesSent < 0)
            perror("Failed to send a message");

    }


    close(fd);

    close(sockFd);

    return 0;

}

Hope this helps

Upvotes: 2

Related Questions