Advertisement
Conchubair

Cx

Mar 5th, 2017
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 8.77 KB | None | 0 0
  1. /**
  2.  
  3.  
  4.         printf("Do you wish to upload or download a file? Enter [u/d] for up or down respectively, followed by the full filename, including the extension. Alternatively press $ to terminate the program");
  5.         >> server is given this info
  6.         parse string, call relevant build function if sending -> sends rdy2rec if receiver & calls relevant accept frame for when data is being sent back
  7.         fileopen read when sending
  8.         gets(request);  // read in the string
  9.  
  10.         for client sender {
  11.         generate byte count for payload
  12.         first n bytes are byte count so insert those
  13.         give in first token of string (u)
  14.         give name of file being sent/received
  15.         }
  16.  
  17.         for server sender {
  18.         generate byte count for payload
  19.         first n bytes are byte count so insert those
  20.         give error/success code
  21.         }
  22.         for both sender
  23.         TESTARRAY[LASTCHAROFHEADER] = '#';  // replace null terminator with CR
  24.         method of loading file into TBS
  25.  
  26.         for client receiver {
  27.         read count so knows how much data to expect
  28.         see if there was an error
  29.         file open to write with user supplied name
  30.         if no error, pipe payload into file
  31.         }
  32.  
  33.         for server receiver {
  34.         read count so knows how much data to expect
  35.         read filename
  36.         file open to write with client supplied name
  37.         pipe payload into file
  38.         }
  39.  
  40.         file close
  41.  
  42.  
  43.         why doesnt client give error codes to the server too?
  44.  
  45.  
  46.  
  47.  
  48.  
  49.  
  50.  
  51.  
  52.  
  53.  
  54.  
  55.  
  56.  
  57. **/
  58.  
  59. #include <stdio.h>
  60. #include <winsock2.h>
  61. #include <ws2tcpip.h>
  62.  
  63. void printError(void);  // function to display error messages
  64.  
  65. int main()
  66. {
  67.     WSADATA wsaData;  // create structure to hold winsock data
  68.     int retVal, nRx, nIn, j;
  69.     int endLine = 0, stop = 0;  // flags to control loops
  70.     char serverIP[20];      // IP address of server
  71.     int serverPort;         // port used by server
  72.     char request[100];      // array to hold user input
  73.     char reply[100];        // array to hold received bytes
  74.  
  75.     // Initialise winsock, version 2.2, giving pointer to data structure
  76.     retVal = WSAStartup(MAKEWORD(2,2), &wsaData);
  77.     if (retVal != 0)  // check for error
  78.     {
  79.         printf("*** WSAStartup failed: %d\n", retVal);
  80.         printError();
  81.         return 1;
  82.     }
  83.     else printf("WSAStartup succeeded\n" );
  84.  
  85.     // Create a handle for a socket, to be used by the client
  86.     SOCKET clientSocket = INVALID_SOCKET;  // handle called clientSocket
  87.  
  88.     // Create the socket, and assign it to the handle
  89.     // AF_INET means IP version 4,
  90.     // SOCK_STREAM means socket works with streams of bytes,
  91.     // IPPROTO_TCP means TCP transport protocol.
  92.     clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  93.     if (clientSocket == INVALID_SOCKET)  // check for error
  94.     {
  95.         printf("*** Failed to create socket\n");
  96.         printError();
  97.         stop = 1;
  98.     }
  99.     else printf("Socket created\n" );
  100.  
  101.     // Get the details of the server from the user
  102.     printf("Enter IP address of server: ");
  103.     scanf("%20s", serverIP);  // get IP address as string
  104.  
  105.     printf("Enter port number: ");
  106.     scanf("%d", &serverPort);     // get port number as integer
  107.  
  108.     gets(request);  // flush the endline from the input buffer
  109.  
  110.     // Build a structure to identify the service required
  111.     // This has to contain the IP address and port of the server
  112.     struct sockaddr_in service;  // IP address and port structure
  113.     service.sin_family = AF_INET;  // specify IP version 4 family
  114.     service.sin_addr.s_addr = inet_addr(serverIP);  // set IP address
  115.     // function inet_addr() converts IP address string to 32-bit number
  116.     service.sin_port = htons(serverPort);  // set port number
  117.     // function htons() converts 16-bit integer to network format
  118.  
  119.     // Try to connect to the service required
  120.     printf("Trying to connect to %s on port %d\n", serverIP, serverPort);
  121.     retVal = connect(clientSocket, (SOCKADDR *) &service, sizeof(service));
  122.     if( retVal != 0)  // check for error
  123.     {
  124.         printf("*** Error connecting\n");
  125.         printError();
  126.         stop = 1;  // make sure we do not go into the while loop
  127.     }
  128.     else printf("Connected!\n");
  129.  
  130.     // Main loop to send messages and receive responses
  131.     // This example assumes client will send first
  132.     while (stop == 0)
  133.     {
  134.         // Get user request and send it to the server
  135.  
  136.  
  137.         printf("Do you wish to upload or download a file? Enter [u/d] for up or down respectively, followed by the full filename, including the extension. Alternatively press $ to terminate the program");
  138.         gets(request);  // read in the string
  139.         // gets() reads until enter (CR), but does not put CR in string
  140.         nIn = strlen(request);  //find the length
  141.  
  142.         /** for downloading **/
  143.  
  144.         /** generate byte count for payload **/
  145.         /** first n bytes are byte count so insert those **/
  146.  
  147.         /** give in first token of string (u or d) **/
  148.         /** give name of file being [up/down]loaded **/
  149.  
  150.         /**TESTARRAY**/[/**LASTCHAROFHEADER**/] = '#';  // replace null terminator with CR
  151.         /**TESTARRAT**/[/**FIRSTPAYLOADCHARACTER**/] = /** method of loading file into TBS **/
  152.  
  153.  
  154.         if (request[0] == '$') stop = 1;  // set stop flag if $ entered
  155.  
  156.         if (stop == 1) printf("Closing connection as requested...\n");
  157.         else  // send the message and try to receive a reply
  158.         {
  159.             // send() arguments: socket handle, array of bytes to send,
  160.             // number of bytes to send, and last argument of 0.
  161.            /** change this retVal = send(clientSocket, request, nIn+2, 0);  // send nIn+2 bytes **/
  162.             // retVal will be number of bytes sent, or error indicator
  163.  
  164.             if( retVal == SOCKET_ERROR) // check for error
  165.             {
  166.                 printf("*** Error sending\n");
  167.                 printError();
  168.             }
  169.             else printf("Sent %d bytes, waiting for reply...\n", retVal);
  170.  
  171.             endLine = 0;
  172.             do  // loop to receive entire reply, terminated by LF
  173.             {
  174.                 // Try to receive some bytes
  175.                 // recv() arguments: socket handle, array to hold rx bytes,
  176.                 // maximum number of bytes to receive, last argument 0.
  177.                 nRx = recv(clientSocket, reply, 100, 0);
  178.                 // nRx will be number of bytes received, or error indicator
  179.  
  180.                 if( nRx == SOCKET_ERROR)  // check for error
  181.                 {
  182.                     printf("Problem receiving\n");
  183.                     //printError();
  184.                     stop = 1;  // exit the loop if problem
  185.                 }
  186.                 else if (nRx == 0)  // connection closed
  187.                 {
  188.                     printf("Connection closed by server\n");
  189.                     stop = 1;
  190.                 }
  191.                 else if (nRx > 0)  // we got some data
  192.                 {
  193.                     for (j = 0; j < nRx; j++)
  194.                     {
  195.                         printf("%c", reply[j]);  // print each character
  196.                         if (reply[j] == 10) endLine = 1;  // found LF
  197.                     }
  198.                 }
  199.             }
  200.             while ((endLine == 0) && (stop == 0));
  201.             // continue until endline or error or connection closed
  202.             // if it was endline, the outer loop should continue
  203.  
  204.         } // end else (not stop)
  205.  
  206.     }  // end while stop == 0
  207.     // When this loop exits, it is time to tidy up and end the program
  208.  
  209.     // Shut down the sending side of the TCP connection first
  210.     retVal = shutdown(clientSocket, SD_SEND);
  211.     if( retVal != 0)  // check for error
  212.     {
  213.         printf("*** Error shutting down sending\n");
  214.         printError();
  215.     }
  216.  
  217.     // Then close the socket
  218.     retVal = closesocket(clientSocket);
  219.     if( retVal != 0)  // check for error
  220.     {
  221.         printf("*** Error closing socket\n");
  222.         printError();
  223.     }
  224.     else printf("Socket closed\n");
  225.  
  226.     // Finally clean up the winsock system
  227.     retVal = WSACleanup();
  228.     printf("WSACleanup returned %d\n",retVal);
  229.  
  230.     // Prompt for user input, so window stays open when run outside CodeBlocks
  231.     printf("\nPress return to exit:");
  232.     gets(request);
  233.     return 0;
  234. }
  235.  
  236. /* Function to print informative error messages
  237.    when something goes wrong...  */
  238. void printError(void)
  239. {
  240.     char lastError[1024];
  241.     int errCode;
  242.  
  243.     errCode = WSAGetLastError();  // get the error code for the last error
  244.     FormatMessage(
  245.         FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  246.         NULL,
  247.         errCode,
  248.         MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  249.         lastError,
  250.         1024,
  251.         NULL);  // convert error code to error message
  252.     printf("WSA Error Code %d = %s\n", errCode, lastError);
  253. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement