Linux under the use of socket transfer file C language simple implementation __linux

Source: Internet
Author: User
Tags htons
simple implementation of C language using socket to transfer files under LinuxCategory: Socket programming 2012-03-03 17:44 4743 people read comments (6) Favorites report Socket language Linux C server buffer

Simple C language Implementation, the client through the TCP protocol to the server to request the transfer of files, the server side received the request to the client to send files.

Server programs and client programs should be running on two computers, respectively.

At the computer terminal running server-side:./file_server

Executes on the compute terminal running the client:./file_client ipaddr_server

Then, depending on the prompts, enter the file on the server you want to transfer, which must be in the current running directory of the server, or you will be prompted not to find the file.

Directly on the source code bar:

[CPP] View Plain copy print?   // file_server.c  -- socket File Transfer server-side sample code   // //////////////////////////////////////////////////////////    #include <netinet/in.h>   #include <sys/types.h>   #include <sys/socket.h>   #include <stdio.h>   #include <stdlib.h>   # include<string.h>      #define  HELLO_WORLD_SERVER_PORT     6666   #define  LENGTH_OF_LISTEN_QUEUE     20   #define   buffer_size                 1024   #define  FILE_NAME_MAX_SIZE         512       Int main (int argc, char **argv)    {   &NBSp;   // set socket ' s address information        //  set a socket address structure server_addr, representing the address and port of the server Internet        struct  sockaddr_in   server_addr;       bzero (&server_addr,  sizeof (SERVER_ADDR));       server_addr.sin_family = AF_INET;        server_addr.sin_addr.s_addr = htons (inaddr_any);        server_addr.sin_port = htons (hello_world_server_port);          // create a stream socket       //   Create a streaming Protocol (TCP) socket for the Internet, an interface that provides services to clients on behalf of the server by Server_socket        int  Server_socket = socket (pf_inet, sock_stream, 0);       if   (server_socket < 0)        {            printf ("create socket failed!\n");           exit (1 );       }          //  Bind the socket and socket address structure        if  (bind server_socket,  (struct  sockaddr*) &server_addr, sizeof (server_addr))        {            printf ("server bind port: %d failed!\n",  Hello_world_server_port);           exit (1);       }          // server_socket for monitoring        if  (Listen (server_socket, length_of_listen_queue))         {           printf ("server listen failed!\n");            exit (1);       }          //  server side has been running to continuously provide services to clients        while (1)        {           //  Defines the socket address structure of the client client_addr, and calls accept           /when a request is received from the client. /  accepts this request and writes the client-side address and port information to client_addr             struct sockaddr_in client_addr;           socklen_t           length = sizeof (CLIENT_ADDR);               //  accepts a connection request from the client side to the server side, Save the client's information in CLIENT_ADDR            //  If there is no connection request, wait until there is a connection request, this is the Accept function feature, you can             //  use Select () to implement timeout detection             // accpet returns a new socket that is used to communicate with the client connected to the server             //  the New_server_socket here represents the communication channel             int new_server_socket = accept (server_socket,  (struct sockaddr*) &client_addr, &length);           if  (new_ server_socket < 0)            {                printf ("server accept failed!\n");                break;            }              char  buffer[BUFFER_SIZE];           bzero (buffer,  sizeof (buffer));           length = recv (new_server _socket, buffer, buffer_size, 0);           if   (length < 0)            {                printf ("server recieve data  failed!\n ");               break;            }               char file_name[FILE_NAME_MAX_SIZE + 1];          &Nbsp; bzero (file_name, sizeof (file_name));            strncpy (file_name, buffer,                    strlen (buffer)  > file_name_max_size ? file_name_max _size : strlen (buffer);              file  *fp = fopen (file_name,  "R");            if  (fp == null)            {                printf ("file:\t%s not found!\n",  file_name);           }            else           {     &Nbsp;         bzero (buffer, buffer_size);                int file_block_length = 0;                while   (file_block_ Length = fread (Buffer, sizeof (char), &NBSP;BUFFER_SIZE,&NBSP;FP))  > 0)                {                    printf ("file_block_length =  %d\n ",  file_block_length);                       //  send a string in buffer to New_server_socket, which is actually sent to the client                    if  Send ( New_server_socket,  buffer, file_block_length, 0)  < 0                     {                        printf ("Send  File:\t%s failed!\n ",  file_name);                        break;                    }                       bzero (Buffer, sizeof ( Buffer));               }               fclose (FP);                printf ("file:\t%s transfer finished!\n",  file_name);            }               close (new_server_socket);       }          close (server_socket);          return 0;   }  


[CPP] View Plain copy print?   // file_client.c   Client-side sample program for socket transfer file   // ///////////////////////////////////////////////////   # include<netinet/in.h>                          // for sockaddr_in    #include <sys/types.h>                           // for socket    #include <sys/socket.h>                          // for socket    #include <stdio.h>                               // for printf    #include <stdlib.h>                              //  for exit   #include <string.h>                               // for bzero      #define  HELLO_WORLD_SERVER_PORT        6666   #define  BUFFER_SIZE                    1024   #define  file_name _max_size            512      Int main (int&NBSP;ARGC,&NBSP;CHAR&NBSP;**ARGV)    {       if  (argc !=  2)        {           printf (" Usage: ./%s serveripaddress\n ",  argv[0]);            exit (1);       }          //  Set a socket address structure client_addr,  represents the client's Internet address and port        struct sockaddr_in  client_addr;       bzero (&client_addr, sizeof (client_addr));        client_addr.sin_family = af_inet; // internet Protocol Family        client_addr.sin_addr.s_addr = htons (inaddr_any);  // INADDR_ Any means to automatically obtain the native address        client_addr.sin_port = htons (0);  // auto  allocated,  lets the system automatically allocate an idle port           //  Create a streaming Protocol (TCP) type socket for the Internet. Use Client_socket to represent the client socket       int client_socket = socket (AF_INET ,  sock_stream, 0);       if  (client_socket < 0)         {           printf ("Create  socket failed!\n ");           exit (1);       }          //  bind client socket to client socket address structure        if  (Bind client_socket,  (struct sockaddr*) &client_addr,  sizeof (CLIENT_ADDR))        {            printf ("client bind port failed!\n");         &nbsP;  exit (1);       }          //   Set a socket address structure server_addr, representing the server's Internet address and port        struct sockaddr_in   server_addr;       bzero (&server_addr, sizeof (SERVER_ADDR));        server_addr.sin_family = AF_INET;        The IP address of the    //  server comes from the parameters of the program        if  (Inet_aton argv[1],  &AMP;SERVER_ADDR.SIN_ADDR)  == 0)        {            printf ("server ip address error!\n");            exit (1);       }          server_addr.sin_port = htons (hello_world_server_port);      &nbsP; socklen_t server_addr_length = sizeof (server_addr);           //  initiates a connection request to the server, after which the client_socket represents a socket connection on the client and server side        if   Connect (client_socket,  (struct sockaddr*) &server_addr, server_addr_length)  <  0)        {            printf ("can not connect to %s!\n",  argv[1]);            exit (1);       }           char file_name[FILE_NAME_MAX_SIZE + 1];       bzero ( File_name, sizeof (file_name));       printf ("Please input file  name on server.\t ");       scanf ("%s ",  file_name);           char buffer[buffer_size];       bzero (buffer, sizeof (buffer));        strncpy (Buffer, file_name, strlen (file_name)  >  Buffer_size ? buffer_size : strlen (file_name));       //   Send data to the server in buffer, when the buffer is stored in the client needs to receive the name of the file        send (client_socket,  buffer, buffer_size, 0);          FILE *fp =  fopen (file_name,  "w");       if  (fp == null)        {           printf ("file:\t%s  Can not open to write!\n ",  file_name);            exit (1);       }           //  fromServer-side receive data to buffer        bzero (buffer, sizeof (buffer));        int length = 0;       while (length =  Recv (client_socket, buffer, buffer_size, 0))        {           if  (length < 0)             {        &n

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.