UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

#1 2009-03-25 04:30 PM

ashrivastava
Member
Registered: 2009-03-25
Posts: 4

Re: socket program to transfer Video file

Does any one have codes to transfer any video file from one machine to another through socket program..please help ...:confused:

Offline

#2 2009-03-25 05:53 PM

i3839
Oddministrator
From: Amsterdam
Registered: 2003-06-07
Posts: 2,239

Re: socket program to transfer Video file

What do you mean?

Do you want to transfer files between different hosts via a network? (scp, ftp)

Do you want to stream video data and display it on different hosts? (vlc)

Offline

#3 2009-03-25 05:54 PM

jfriesne
Administrator
From: California
Registered: 2005-07-06
Posts: 348
Website

Re: socket program to transfer Video file

Offline

#4 2009-03-26 07:29 AM

ashrivastava
Member
Registered: 2009-03-25
Posts: 4

Re: socket program to transfer Video file

dear jeremy,
  Thanks for the reply .. actually i first want to break a video file into  parts
and send these parts one by one  to another host through socket.

Offline

#5 2009-03-26 05:54 PM

jfriesne
Administrator
From: California
Registered: 2005-07-06
Posts: 348
Website

Re: socket program to transfer Video file

Well, below is some code that demonstrates transferring a file over a TCP connection.  Note that I only compiled and tested this code under MacOS/X; it should work under Linux and Windows but might require some minor tweaking on those platforms.

To run it, open up two shell windows (either both on the same machine, or on different machines).  In one, run it like this:

./a.out receive filename_to_create.txt 9999

Then, in the other, run it like this:

./a.out send filename_to_send.txt 127.0.0.1:9999

(if the receiver is on a different machine than the sender, replace 127.0.0.1 with the IP address of the receiver machine).

If all is successful, you will see output in both windows indicating data is being transferred, and at the end, both programs will exit, and there will be a file filename_to_create.txt on the receiving machine that is identical to filename_to_send.txt is on the sending machine.

Hope that helps,
Jeremy

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <netinet/in.h>
#include <unistd.h>

typedef unsigned long ip_address;
typedef unsigned short uint16;

static const int BUFFER_SIZE = 16*1024;

static void UsageExit()
{
   printf("Usage:  xfer (send/receive) filename [host:Port]\n");
   exit(10);
}

static ip_address GetHostByName(const char * name)
{
   struct hostent * he = gethostbyname(name);
   return ntohl(he ? *((ip_address*)he->h_addr) : 0);
}

static void SendFile(ip_address ipAddress, uint16 port, const char * fileName)
{
   FILE * fpIn = fopen(fileName, "r");
   if (fpIn)
   {
      int s = socket(AF_INET, SOCK_STREAM, 0);
      if (s >= 0)
      {
         struct sockaddr_in saAddr; memset(&saAddr, 0, sizeof(saAddr));
         saAddr.sin_family      = AF_INET;
         saAddr.sin_addr.s_addr = htonl(ipAddress);
         saAddr.sin_port        = htons(port);

         if (connect(s, (struct sockaddr *) &saAddr, sizeof(saAddr)) == 0)
         {
            printf("Connected to remote host, sending file [%s]\n", fileName);

            char buf[BUFFER_SIZE];
            while(1)
            {
               ssize_t bytesRead = fread(buf, 1, sizeof(buf), fpIn);
               if (bytesRead <= 0) break;  // EOF

               printf("Read %i bytes from file, sending them to network...\n", (int)bytesRead);
               if (send(s, buf, bytesRead, 0) != bytesRead)
               {
                  perror("send");
                  break;
               }
            }
         }
         else perror("connect");

         close(s);
      }
      else perror("socket");

      fclose(fpIn);
   }
   else printf("Error, couldn't open file [%s] to send!\n", fileName);
}

static void ReceiveFile(uint16 port, const char * fileName)
{
   int s = socket(AF_INET, SOCK_STREAM, 0);
   if (s >= 0)
   {
#ifndef WIN32
      // (Not necessary under windows -- it has the behaviour we want by default)
      const int trueValue = 1;
      (void) setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &trueValue, sizeof(trueValue));
#endif

      struct sockaddr_in saAddr; memset(&saAddr, 0, sizeof(saAddr));
      saAddr.sin_family      = AF_INET;
      saAddr.sin_addr.s_addr = htonl(0);  // (IPADDR_ANY)
      saAddr.sin_port        = htons(port);

      if ((bind(s, (struct sockaddr *) &saAddr, sizeof(saAddr)) == 0)&&(listen(s, 10) == 0))
      {
         memset(&saAddr, 0, sizeof(saAddr));
         socklen_t len = sizeof(saAddr);
         printf("Waiting for incoming TCP connection on port %u, to write file [%s]\n", port, fileName);
         int connectSocket = accept(s, (struct sockaddr *) &saAddr, &len);
         if (connectSocket >= 0)
         {
            FILE * fpIn = fopen(fileName, "w");
            if (fpIn)
            {
               char buf[BUFFER_SIZE];
               while(1)
               {
                  ssize_t bytesReceived = recv(connectSocket, buf, sizeof(buf), 0);
                  if (bytesReceived < 0) perror("recv");  // network error?
                  if (bytesReceived == 0) break;   // sender closed connection, must be end of file

                  printf("Received %i bytes from network, writing them to file...\n", (int) bytesReceived);
                  if (fwrite(buf, 1, bytesReceived, fpIn) != (size_t) bytesReceived)
                  {
                     perror("fwrite");
                     break;
                  }
               }

               fclose(fpIn);
            }
            else printf("Error, couldn't open file [%s] to receive!\n", fileName);

            close(connectSocket);
         }
      }
      else perror("bind");

      close(s);
   }
   else perror("socket");
}

int main(int argc, char ** argv)
{
   if (argc < 4) UsageExit();

#ifdef WIN32
   // Windows requires this to start up the networking API
   WORD versionWanted = MAKEWORD(1, 1);
   WSADATA wsaData;
   (void) WSAStartup(versionWanted, &wsaData);
#else 
   // avoid SIGPIPE signals caused by sending on a closed socket
   signal(SIGPIPE, SIG_IGN);
#endif

   bool isSend = false;
        if (strcmp(argv[1], "send")    == 0) isSend = true;
   else if (strcmp(argv[1], "receive") != 0) UsageExit();

   const char * fileName = argv[2];

   ip_address ip = isSend ? GetHostByName(argv[3]) : 0;
   uint16 port = 0;
   const char * portColon = strchr(argv[3], ':');
   port = portColon ? atoi(portColon+1) : 0;
   if (port == 0) port = 9999;

   if (isSend) SendFile(ip, port, fileName);
          else ReceiveFile(port, fileName);

   printf("Exiting, bye!\n");
   return 0;
}

Offline

#6 2009-03-27 06:10 AM

ashrivastava
Member
Registered: 2009-03-25
Posts: 4

Re: socket program to transfer Video file

dear jeremy,
   A lot of thanks...one more question i have previously tried a similar type of code ..it was sending text file easily from server to client but is it possible to send video file , i mean in your code where file name is to be mentioned if i write
name of any video file will it do.

Offline

#7 2009-03-27 04:57 PM

jfriesne
Administrator
From: California
Registered: 2005-07-06
Posts: 348
Website

Re: socket program to transfer Video file

Offline

#8 2009-04-03 02:29 PM

ashrivastava
Member
Registered: 2009-03-25
Posts: 4

Re: socket program to transfer Video file

hi jeremy ...now i am able to transfer  the files..thanks..:cool:

Offline

#9 2010-12-29 03:15 PM

Dionei
Guest

Re: socket program to transfer Video file

Hi,

        I'm brazilian and i'm written just to thank you Jeremy for you source code to file transfer with sockets. It helped us a lot.

Thanks.

Dionei.

#10 2011-08-19 05:13 PM

developwyo
Member
Registered: 2011-08-16
Posts: 6

Re: socket program to transfer Video file

Last edited by developwyo (2011-09-22 05:44 PM)

Offline

#11 2012-03-27 09:17 AM

Ram
Guest

Re: socket program to transfer Video file

can u help me with the code for splitting(into smaller packets) & transferring a video file(any kind) from server to a client implemented in java using Socket programming.

#12 2012-03-30 11:48 AM

Maharathi_
Guest

Re: socket program to transfer Video file

Even i need codes for sending video files using socket programming.. can anybody help me?

#13 2012-04-01 01:51 AM

i3839
Oddministrator
From: Amsterdam
Registered: 2003-06-07
Posts: 2,239

Re: socket program to transfer Video file

Guys, if you want help then you need to ask specific questions.

Ram: Just post your code and tell us what the problem is. We'll try to help even if it's Java code.
Start a new thread for this.

Maharathi: Jeremy posted some C++ code to transfer any type of file.

Offline

#14 2013-12-24 08:00 AM

sarika
Guest

Re: socket program to transfer Video file

hi jeremy

   This is sarika  and I just want to say  thank you Jeremy for you  code to file transfer with sockets. It helped us a lot.
Thank you very much .......

#15 2014-03-11 04:34 PM

sak
Guest

Re: socket program to transfer Video file

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <netinet/in.h>
#include <unistd.h>

typedef unsigned long ip_address;
typedef unsigned short uint16;

static const int BUFFER_SIZE = 16*1024;

static void UsageExit()
{
   printf("Usage:  xfer (send/receive) filename [host:Port]\n");
   exit(10);
}

static ip_address GetHostByName(const char * name)
{
   struct hostent * he = gethostbyname(name);
   return ntohl(he ? *((ip_address*)he->h_addr) : 0);
}

static void SendFile(ip_address ipAddress, uint16 port, const char * fileName)
{
   FILE * fpIn = fopen(fileName, "r");
   if (fpIn)
   {
      int s = socket(AF_INET, SOCK_STREAM, 0);
      if (s >= 0)
      {
         struct sockaddr_in saAddr; memset(&saAddr, 0, sizeof(saAddr));
         saAddr.sin_family      = AF_INET;
         saAddr.sin_addr.s_addr = htonl(ipAddress);
         saAddr.sin_port        = htons(port);

         if (connect(s, (struct sockaddr *) &saAddr, sizeof(saAddr)) == 0)
         {
            printf("Connected to remote host, sending file [%s]\n", fileName);

            char buf[BUFFER_SIZE];
            while(1)
            {
               ssize_t bytesRead = fread(buf, 1, sizeof(buf), fpIn);
               if (bytesRead <= 0) break;  // EOF

               printf("Read %i bytes from file, sending them to network...\n", (int)bytesRead);
               if (send(s, buf, bytesRead, 0) != bytesRead)
               {
                  perror("send");
                  break;
               }
            }
         }
         else perror("connect");

         close(s);
      }
      else perror("socket");

      fclose(fpIn);
   }
   else printf("Error, couldn't open file [%s] to send!\n", fileName);
}

static void ReceiveFile(uint16 port, const char * fileName)
{
   int s = socket(AF_INET, SOCK_STREAM, 0);
   if (s >= 0)
   {
#ifndef WIN32
      // (Not necessary under windows -- it has the behaviour we want by default)
      const int trueValue = 1;
      (void) setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &trueValue, sizeof(trueValue));
#endif

      struct sockaddr_in saAddr; memset(&saAddr, 0, sizeof(saAddr));
      saAddr.sin_family      = AF_INET;
      saAddr.sin_addr.s_addr = htonl(0);  // (IPADDR_ANY)
      saAddr.sin_port        = htons(port);

      if ((bind(s, (struct sockaddr *) &saAddr, sizeof(saAddr)) == 0)&&(listen(s, 10) == 0))
      {
         memset(&saAddr, 0, sizeof(saAddr));
         socklen_t len = sizeof(saAddr);
         printf("Waiting for incoming TCP connection on port %u, to write file [%s]\n", port, fileName);
         int connectSocket = accept(s, (struct sockaddr *) &saAddr, &len);
         if (connectSocket >= 0)
         {
            FILE * fpIn = fopen(fileName, "w");
            if (fpIn)
            {
               char buf[BUFFER_SIZE];
               while(1)
               {
                  ssize_t bytesReceived = recv(connectSocket, buf, sizeof(buf), 0);
                  if (bytesReceived < 0) perror("recv");  // network error?
                  if (bytesReceived == 0) break;   // sender closed connection, must be end of file

                  printf("Received %i bytes from network, writing them to file...\n", (int) bytesReceived);
                  if (fwrite(buf, 1, bytesReceived, fpIn) != (size_t) bytesReceived)
                  {
                     perror("fwrite");
                     break;
                  }
               }

               fclose(fpIn);
            }
            else printf("Error, couldn't open file [%s] to receive!\n", fileName);

            close(connectSocket);
         }
      }
      else perror("bind");

      close(s);
   }
   else perror("socket");
}

int main(int argc, char ** argv)
{
   if (argc < 4) UsageExit();

#ifdef WIN32
   // Windows requires this to start up the networking API
   WORD versionWanted = MAKEWORD(1, 1);
   WSADATA wsaData;
   (void) WSAStartup(versionWanted, &wsaData);
#else 
   // avoid SIGPIPE signals caused by sending on a closed socket
   signal(SIGPIPE, SIG_IGN);
#endif

   bool isSend = false;
        if (strcmp(argv[1], "send")    == 0) isSend = true;
   else if (strcmp(argv[1], "receive") != 0) UsageExit();

   const char * fileName = argv[2];

   ip_address ip = isSend ? GetHostByName(argv[3]) : 0;
   uint16 port = 0;
   const char * portColon = strchr(argv[3], ':');
   port = portColon ? atoi(portColon+1) : 0;
   if (port == 0) port = 9999;

   if (isSend) SendFile(ip, port, fileName);
          else ReceiveFile(port, fileName);

   printf("Exiting, bye!\n");
   return 0;
}

#16 2014-03-11 04:38 PM

sak
Guest

Re: socket program to transfer Video file

Hi jeremy,
how can i implement that TCP file transfer code(what u have implemented  before ) over UDP to transfer any type of file..

#17 2014-06-10 12:01 PM

pa
Guest

Re: socket program to transfer Video file

how do i execute the code provided by jeremy on windows 7.I am new to socket programming and i have to transfer a video file from server to client which are hosted on the same pc.thankful for the replies.

#18 2014-06-10 12:29 PM

RobSeace
Administrator
From: Boston, MA
Registered: 2002-06-12
Posts: 3,839
Website

Re: socket program to transfer Video file

Well, you'll first need a C compiler (C++ will probably suffice as well)...  It looks like he's already coded in some Win32 support, so it may not need anything other than that to get it running...  But, I couldn't tell you, as I haven't used any version of Windows since Win95, and don't plan on ever using any ever again in my life!  But, maybe someone else here who has the misfortune of running Windows and has a compiler onhand already can whip you up a compiled binary?

Offline

#19 2014-06-10 01:35 PM

pa
Guest

Re: socket program to transfer Video file

will visual studio compiler work?

#20 2014-06-10 07:41 PM

RobSeace
Administrator
From: Boston, MA
Registered: 2002-06-12
Posts: 3,839
Website

Re: socket program to transfer Video file

I really have no idea...  Like I said, I don't use Windows and haven't for ages, so I'm blissfully unfamiliar with anything in that realm of horror...  But, assuming it's a C/C++ compiler, I can't imagine why it shouldn't work...

Offline

#21 2014-06-11 09:18 AM

shruti
Guest

Re: socket program to transfer Video file

is the code provided above correct?i am getting errors when compiling in turbo c++ and am not able to run it.kindly help.

#22 2014-06-11 11:53 AM

RobSeace
Administrator
From: Boston, MA
Registered: 2002-06-12
Posts: 3,839
Website

Re: socket program to transfer Video file

What errors exactly?  I just tried compiling it with GCC, and I had to add #include's for two headers: <signal.h> and <stdbool.h>...  Without those, it does indeed complain...  But, with those added, it seems to compile cleanly...

Offline

#23 2014-06-11 12:58 PM

shruti
Guest

Re: socket program to transfer Video file

it is showing errors in header files like<sys/socket.h> <netinet/in.h> and <unistd.h>.it is showing that it cannot open source files.
i think it will work well with unix based operating system.for windows we need to program it differently.thanx anyways.

#24 2014-07-18 08:07 AM

rohin
Guest

Re: socket program to transfer Video file

i am compiling same code under linux in ubuntu
getting error in connect function on send side
using two different sysytem both are ubuntu
not able to share file between them
but on single system with two terminal it works file need help

#25 2014-07-18 12:19 PM

RobSeace
Administrator
From: Boston, MA
Registered: 2002-06-12
Posts: 3,839
Website

Re: socket program to transfer Video file

Offline

Board footer

Powered by FluxBB