FTP program

This is a discussion on FTP program within the Linux Programming forums, part of the Platform Specific Boards category; Simple question here. Im a fairly experienced programmer. But ive never programed with sockets and never programed for linux. Im ...

  1. #1
    Registered User
    Join Date
    Sep 2008
    Posts
    30

    FTP program

    Simple question here. Im a fairly experienced programmer. But ive never programed with sockets and never programed for linux. Im running fedora 9 on another computer of mine and I have a simple socket program written with a server and client connecting to each other and sending a simple message from server to client each time the client connects to the server. I totally understand all the code, but my big question is. How would you transfer files not just simple messages? I looked through the API's and there's only simple read() write() functions for sockets. Does this mean that you have to somehow open a file on the server read it into an array and have the client read the array and put the data into a file onto the clients machine? Im just looking for a hint in the right direction I don't need anyone to write the code, but for some reason it seems that transferring files through sockets is a rare topic and more people talk about sending simple messages. Any help is appreciated. Im programming in the C language.
    Last edited by jakemott; 09-29-2008 at 04:41 PM.

  2. #2
    Chinese pâté foxman's Avatar
    Join Date
    Jul 2007
    Location
    Canada
    Posts
    404
    Does this mean that you have to somehow open a file on the server read it into an array and have the client read the array and put the data into a file onto the clients machine?
    Yes. At the socket level (which translate to the transport layer), you don't transfer files, you transfer bytes. You need another layer to reach the abstraction of transfering files.
    I hate real numbers.

  3. #3
    Registered User
    Join Date
    Sep 2008
    Posts
    30
    k, Took me about 5 hours but I brushed up on file streams and I/O and all that good stuff and wrote it up. all the file handling code is at the bottom of the client and server .c file respectively. The top portion of the server.c and client.c is all pretty much similar it just sets up basic comms. Its the bottom where the File transferring takes place. Im getting no errors on compile, but when The server sends the "Enter your filename request" and I type it and hit enter, the server throws the if (funny == NULL) printf("File doesn't exist\n");
    and then a segmentation fault. So im trying to figure out why the file is NULL? Ive highlighted the significant code in green.




    CLIENT CODE

    Code:
    /* client.c - code for example client program that uses TCP */
    #ifndef unix
    #define WIN32
    #include <windows.h>
    #include <winsock.h>
    #else
    #define closesocket close
    #include <sys/types.h>
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <arpa/inet.h>
    #include <netdb.h>
    #endif
    #include <stdio.h>
    #include <string.h>
    #define PROTOPORT 5193 /* default protocol port number */
    extern int errno;
    char localhost[] = "localhost"; /* default host name */
    /*------------------------------------------------------------------------
     * * Program: client
     * *
     * * Purpose: allocate a socket, connect to a server, and print all output
     * * Syntax: client [ host [port] ]
     * *
     * * host - name of a computer on which server is executing
     * * port - protocol port number server is using
     * *
     * * Note: Both arguments are optional. If no host name is specified,
     * * the client uses "localhost"; if no protocol port is
     * * specified, the client uses the default given by PROTOPORT.
     * *
     * *------------------------------------------------------------------------
     * */
    main(argc, argv)
    	int argc;
    	char *argv[];
    {
    	struct hostent *ptrh; /* pointer to a host table entry */
    	struct protoent *ptrp; /* pointer to a protocol table entry */
    	struct sockaddr_in sad; /* structure to hold an IP address */
    	int sd; /* socket descriptor */
    	int port; /* protocol port number */
    	//char *host; /* pointer to host name */
    	int n; /* number of characters read */
    	char *host, buf[1000], *pt, out[1000] = "DOWNLOADEDFILE.TXT"; /* buffer for data from the server */
    	FILE *funny;
    	pt = buf;
    #ifdef WIN32
    	WSADATA wsaData;
    	WSAStartup(0x0101, &wsaData);
    #endif
    	memset((char *)&sad,0,sizeof(sad)); /* clear sockaddr structure */
    	sad.sin_family = AF_INET; /* set family to Internet */
    	/* Check command-line argument for protocol port and extract */
    	/* port number if one is specified. Otherwise, use the default */
    	/* port value given by constant PROTOPORT */
    	if (argc > 2) { /* if protocol port specified */
    		port = atoi(argv[2]); /* convert to binary */
    	} else {
    		port = PROTOPORT; /* use default port number */
    	}
    	if (port > 0) /* test for legal value */
    		sad.sin_port = htons((u_short)port);
    	else { /* print error message and exit */
    		fprintf(stderr,"bad port number &#37;s\n",argv[2]);
    		exit(1);
    	}
    	/* Check host argument and assign host name. */
    	if (argc > 1) {
    		host = argv[1]; /* if host argument specified */
    	} else {
    		host = localhost;
    	}
    	/* Convert host name to equivalent IP address and copy to sad. */
    	ptrh = gethostbyname(host);
    	if ( ((char *)ptrh) == NULL ) {
    		fprintf(stderr,"invalid host: %s\n", host);
    		exit(1);
    	}
    	memcpy(&sad.sin_addr, ptrh->h_addr, ptrh->h_length);
    	/* Map TCP transport protocol name to protocol number. */
    	if ( ((int)(ptrp = getprotobyname("tcp"))) == 0) {
    		fprintf(stderr, "cannot map \"tcp\" to protocol number");
    		exit(1);
    	}
    	/* Create a socket. */
    	sd = socket(PF_INET, SOCK_STREAM, ptrp->p_proto);
    	if (sd < 0) {
    		fprintf(stderr, "socket creation failed\n");
    		exit(1);
    	}
    	/* Connect the socket to the specified server. */
    	if (connect(sd, (struct sockaddr *)&sad, sizeof(sad)) < 0) {
    		fprintf(stderr,"connect failed\n");
    		exit(1);
    	}
    	/* */
    	n = recv(sd, buf, sizeof(buf), 0);
    	if (n > 0) 
    		printf(buf);
    	memset((char *)&buf,0,sizeof(buf));
    	while ((*pt++ = getchar()) != '\n');
    		*pt = '\0';
    	send(sd, buf, sizeof(buf),0);
    	recv(sd, buf, sizeof(buf), 0);
    	while((*pt++ = getchar()) != '\n');
    		*pt = '\0';
    	funny = fopen(buf, "w");
    	fprintf(funny, "%s \n", buf);
    
    	fclose(funny);
    
    	/* Close the socket. */
    	closesocket(sd);
    	/* Terminate the client program gracefully. */
    	exit(0);
    }
    SERVER CODE


    Code:
    /* server.c - code for example server program that uses TCP */
    #ifndef unix
    #define WIN32
    #include <windows.h>
    #include <winsock.h>
    #else
    #define closesocket close
    #include <sys/types.h>
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <netdb.h>
    #endif
    #include <stdio.h>
    #include <string.h>
    #define PROTOPORT 5193 /* default protocol port number */
    #define QLEN 6 /* size of request queue */
    int visits = 0; /* counts client connections */
    /*------------------------------------------------------------------------
     * * Program: server
     * *
     * * Purpose: allocate a socket and then repeatedly execute the following:
     * * (1) wait for the next connection from a client
     * * (2) send a short message to the client
     * * (3) close the connection
     * * (4) go back to step (1)
     * * Syntax: server [ port ]
     * *
     * * port - protocol port number to use
     * *
     * * Note: The port argument is optional. If no port is specified,
     * * the server uses the default given by PROTOPORT.
     * *
     * *------------------------------------------------------------------------
     * */
    main(argc, argv)
    	int argc;
    	char *argv[];
    {
    	struct hostent *ptrh; /* pointer to a host table entry */
    	struct protoent *ptrp; /* pointer to a protocol table entry */
    	struct sockaddr_in sad; /* structure to hold server.s address */
    	struct sockaddr_in cad; /* structure to hold client.s address */
    	int sd, sd2; /* socket descriptors */
    	int port; /* protocol port number */
    	int alen; /* length of address */
    	char buf[1000] = "Enter your filename request", c, *p; /* buffer for string the server sends */
    	FILE *funny;
    	p = buf;
    #ifdef WIN32
    	WSADATA wsaData;
    	WSAStartup(0x0101, &wsaData);
    #endif
    	memset((char *)&sad,0,sizeof(sad)); /* clear sockaddr structure */
    	sad.sin_family = AF_INET; /* set family to Internet */
    	sad.sin_addr.s_addr = INADDR_ANY; /* set the local IP address */
    	/* Check command-line argument for protocol port and extract */
    	/* port number if one is specified. Otherwise, use the default */
    	/* port value given by constant PROTOPORT */
    	if (argc > 1) { /* if argument specified */
    		port = atoi(argv[1]); /* convert argument to binary */
    	} else {
    		port = PROTOPORT; /* use default port number */
    	}
    	if (port > 0) /* test for illegal value */
    		sad.sin_port = htons((u_short)port);
    	else { /* print error message and exit */
    		fprintf(stderr,"bad port number %s\n",argv[1]);
    		exit(1);
    	}
    	/* Map TCP transport protocol name to protocol number */
    	if ( ((int)(ptrp = getprotobyname("tcp"))) == 0) {
    		fprintf(stderr, "cannot map \"tcp\" to protocol number");
    		exit(1);
    	}
    	/* Create a socket */
    	sd = socket(PF_INET, SOCK_STREAM, ptrp->p_proto);
    	if (sd < 0) {
    		fprintf(stderr, "socket creation failed\n");
    		exit(1);
    	}
    	/* Bind a local address to the socket */
    	if (bind(sd, (struct sockaddr *)&sad, sizeof(sad)) < 0) {
    		fprintf(stderr,"bind failed\n");
    		exit(1);
    	}
    	/* Specify size of request queue */
    	if (listen(sd, QLEN) < 0) {
    		fprintf(stderr,"listen failed\n");
    		exit(1);
    	}
    	/* Main server loop - accept and handle requests */
    	while (1) {
    		alen = sizeof(cad);
    		if ( (sd2=accept(sd, (struct sockaddr *)&cad, &alen)) < 0) {
    			fprintf(stderr, "accept failed\n");
    			exit(1);
    		}
    		send(sd2,buf,strlen(buf),0);
    		memset((char *)&buf, 0, sizeof(buf));
    		recv(sd2,buf,strlen(buf),0);
    		funny = fopen(buf, "r");
    		if (funny == NULL) printf("File doesn't exist\n");
    		else {
    			do {
    				c = getc(funny);
    				*p++ = c;
    			}while (c != EOF);
    		
    		}
    		fclose(funny);
    		send(sd2,buf,strlen(buf),0);
    		closesocket(sd2);
    	}
    }
    Last edited by jakemott; 09-29-2008 at 11:35 PM.

  4. #4
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,417
    > main(argc, argv)
    > int argc;
    > char *argv[];
    This style of C hasn't been valid for 20 years - where have you been?

    > printf(buf);
    http://en.wikipedia.org/wiki/Format_string_attack
    NEVER DO THIS!
    Passing unknown strings as the format string to printf is just asking for trouble these days.

    > n = recv(sd, buf, sizeof(buf), 0);
    I see you make a lot of calls to memset, but sadly not on the first pass. So your buffer is tail-filled with garbage.
    Even with that, it's still wrong. If recv() actually fills the buffer to capacity, then there is NO ROOM for a \0.
    Consider this, which also means you don't have to keep calling memset every time.

    n = recv(sd, buf, sizeof(buf)-1, 0);
    if ( n > 0 ) buf[n] = '\0';

    > while((*pt++ = getchar()) != '\n');
    OK, the 2nd time you call this, has pt been reset back to the start of the buffer?
    Also, this loop locks up (and trashes memory) if you press ctrl-d (also known as EOF).

    > send(sd2,buf,strlen(buf),0);
    Always check the return result. It's YOUR responsibility to do this
    send() may return a number which is LESS than the amount you asked to be sent. In this case, you need to call send() again with the fragment of the data which was not sent.

    Probably some other stuff as well, but I've got to go.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  5. #5
    Registered User
    Join Date
    Sep 2008
    Posts
    30
    Well, still been working on this thing for god knows how long. C seems pretty buggy. Here's what Ive come up with for the FTP part of the program. The rest of the program is still the same so no need to repost it. Problem im having now is I cant get the data in the file_buffer once it is transfered to the client to write to the file thats been opened for it. I think its being printed onto the screen someone through fputs(file_buffer, fp). ??? I highlighted the fputs() code in green in the client section for easy find. Someone mind taking a look please. Heres the code.

    Client

    Code:
    	n = recv(sd, buf_recv, sizeof(buf_recv), 0);
    
    	
    
    	buf_recv[n]='\0';
    
    	printf("&#37;s",buf_recv);
    
    	scanf("%s",buf_send);
    
    	send(sd,buf_send,strlen(buf_send),0);
    
    	n = recv(sd, buf_recv, sizeof(buf_recv), 0);
    
    	
    
    	buf_recv[n]='\0';
    
    	printf("%s",buf_recv);
    
    	fflush(stdout);
    
    	
    
    	n=recv(sd, file_buffer, sizeof(file_buffer), 0);
    
    	file_buffer[n]='\0';
    
    	printf("%s %d\n",file_buffer,n);
    
    	fflush(stdout);
    
    	fp = fopen("DOWNLOADED.TXT","w");
    
    	fputs(file_buffer,fp);
    	fclose(fp);
    
    	closesocket(sd);
    
    	/* Terminate the client program gracefully. */
    
    	exit(0);


    Server


    Code:
    sprintf(buf_send,"Please enter the file name: ");
    
    
    
    		send(sd2,buf_send,strlen(buf_send),0);
    
    		n=recv(sd2,buf_recv,1000,0);
    
    		buf_recv[n]='\0';
    
    		printf("%s",buf_recv);
    
    		fflush(stdout);
    
    
    
    		if((fp = fopen(buf_recv,"r"))==NULL)
    
    			{
    
    			sprintf(buf_send,"File could not be found!!!");
    
    			exit(0);
    
    			}
    
    		else
    
    			sprintf(buf_send,"File found!!!\n");
    
    		
    
    		send(sd2,buf_send,strlen(buf_send),0);
    
    		while(!feof(fp))
    
    		{
    
    			if (feof(fp))
    			break;
    			fgets(f_buffer,1000,fp);
    
    			strcat(file_buffer,f_buffer);
    			if (feof(fp))
    			break;
    
    		}
    
    		fclose(fp);
    
    		send(sd2,file_buffer,strlen(file_buffer),0);
    
    		closesocket(sd2);
    
    	//}
    
    		//closesocket(sd);
    
    		exit(0);

  6. #6
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    The printf is what's putting the text on the screen. Was the file DOWNLOADED.TXT created? Is it completely empty? Did the fopen call succeed?

  7. #7
    Registered User
    Join Date
    Sep 2008
    Posts
    30
    Yeah, the file DOWNLOADED.TXT was created in the client folder. But like you said it was completely empty. My confusion is this code below from the client.

    Code:
    buf_recv[n]='\0';
    
    printf("&#37;s",buf_recv);
    
    fflush(stdout);
    Is that what your saying is printing the file_buffer contents?

    Because its only supposed to print this code from the server.

    Code:
    sprintf(buf_send,"File could not be found!!!");
    
    			exit(0);
    
    			}
    
    		else
    
    			sprintf(buf_send,"File found!!!\n");
    from the server code.

    and then the file_buffer contents shouldn't even be output to the screen it should get put in the DOWNLOADED.TXT file???

    Like I said Ive been debugging this thing for a while, and im at a loss.

  8. #8
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    No, I would guess that this line
    Code:
    printf("%s %d\n",file_buffer,n);
    prints out the file buffer (and as a bonus, its size).

    By the way, I'm pretty sure you should never use strlen(buf) in a recv call -- it should be sizeof(buf).

  9. #9
    Registered User
    Join Date
    Sep 2008
    Posts
    30
    Arrrr... thought I had that commented out. Yeah that will print it to the screen. But the funny thing is that when you comment that out of the code, the file_buffer contents is somehow still printed to the screen?? lol, and also the file DOWNLOADED.TXT still is empty.

    I looked through the code, I couldn't find any recv() function with strlen used in it. I saw a bunch of send() functions with it though. Should send() not use strlen either?

  10. #10
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    I was looking at the green code in the original post in the server. Maybe that's gone now, I don't know. send can use strlen, that's fine.

    So that buf_recv should be "File found!!!!" and not, say, the file itself, as I'm reading the code. You could put the name of what your printing in your debug printf's to make sure of that. And printing out file_buffer and n will at least make sure that got read correctly.

  11. #11
    Registered User
    Join Date
    Sep 2008
    Posts
    30
    Quote Originally Posted by tabstop View Post
    I
    So that buf_recv should be "File found!!!!" and not, say, the file itself, as I'm reading the code.
    Correct.

    Ok so I put this in the client code right below the buf_recv that prints out File found!!!.

    Code:
    buf_recv[n]='\0';
    
    	printf("&#37;s",buf_recv);
    
    	fflush(stdout);
    
    	printf("End of buf_recv");
    
    	fflush(stdout);



    Which as a matter of fact it does so the server does find the file. of course we know this because the client prints its contents to the screen. lol, but It won't put it in the file. rarrr! .


    Anyways so the contents of DOWNLOAD.TXT are

    This is a test.
    Woooo it worked.
    Woooo it worked.


    and this is what the code above prints.

    File found!!!
    This is a test.
    Woooo it worked.
    Woooo it worked.
    End of buf_recv

    So somehow

    Code:
    buf_recv[n]='\0';
    
    	printf("%s",buf_recv);
    
    	fflush(stdout);

    Is printing the file_buffer contents to the screen, and im guessing this is making it not be able to be put into the DOWNLOADED.TXT file??

    fflush(stdout) isnt printing it to the screen is it?

  12. #12
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    So maybe this is my complete and total lack of ever having done network stuff but: why can't two send calls be picked up by one recv call? send doesn't block, I don't think, so if the client doesn't call recv until both sends have been done, won't it see one big pile of buffer?

    But by the output, at any rate, everything's in buf_recv and nothing's in file_buf.

  13. #13
    Registered User
    Join Date
    Sep 2008
    Posts
    30
    lol, yeah I was kinda dreading that. This is my first time to mess around with sockets/network code. I belive that is exactly what is happening though, even though I was kinda in denial cause now I need to figure out how to fix that. At any rate thank you for all your help, it was very useful. Im gonna see If I can find anything about this subject on the net. Got to be some way to control the send and recv calls.

  14. #14
    Registered User
    Join Date
    Sep 2008
    Posts
    30
    Figured it out. Lol, kinda makes sense. Ok, so I just used the idea that everytime the server sends the client something the client needs to send the server something and the server recvs it.

    So this code, the green part in particular.

    Code:
    buf_recv[n]='\0';
    
    printf("&#37;s",buf_recv);
    
    fflush(stdout);
    	
    send(sd,buf_send, strlen(buf_send),0);
    makes sure that the server doesn't send its next part until it recvs something from the client.
    Thus controling it.

    Heres the server code. Green part is the added recv()

    Code:
    if((fp = fopen(buf_recv,"r"))==NULL)
    
    			{
    
    			sprintf(buf_send,"File could not be found!!!");
    
    			exit(0);
    
    			}
    
    		else
    
    			sprintf(buf_send,"File found!!!\n");
    
    		
    
    		send(sd2,buf_send,strlen(buf_send),0);
    
    		n=recv(sd2,buf_recv,1000,0);
    
    
    		while(!feof(fp))
    
    		{
    
    			if (feof(fp))
    			break;
    			fgets(f_buffer,1000,fp);
    
    			strcat(file_buffer,f_buffer);
    			if (feof(fp))
    			break;
    
    		}
    As you can see it sends the "File found" but if thers no recv in between that and the while loop below that sends the file_buffer then they both get sent together. So i just threw that recv in there and it doesn't actually do anything it just puts a pause in between those two sends from the server.

  15. #15
    Registered User
    Join Date
    Sep 2008
    Posts
    30
    Here's the final code for server.c and client.c. In case anyone needs an example of how to transfer a file. I know I could have used one. Would have saved me lots of hours of toil. I fixed some other things so don't use any original code, otherwise you might get double the txt in your new downloaded file as I was getting and had to debug to fix it. Also this has only been run on linux, not sure how it will hold up on windows. The green code is what does the talking/file transfering the rest of the previous code above that in both client and server is just setting up the socket.

    Server.c

    Code:
    /* server.c - code for example server program that uses TCP */
    
    #ifndef unix
    
    #define WIN32
    
    #include <windows.h>
    
    #include <winsock.h>
    
    #else
    
    #define closesocket close
    
    #include <sys/types.h>
    
    #include <sys/socket.h>
    
    #include <netinet/in.h>
    
    #include <stdlib.h>
    
    #include <netdb.h>
    
    #endif
    
    #include <stdio.h>
    
    #include <string.h>
    
    #define PROTOPORT 5193 /* default protocol port number */
    
    #define QLEN 6 /* size of request queue */
    
    int visits = 0; /* counts client connections */
    
    /*------------------------------------------------------------------------
    
     * * Program: server
    
    
     * * Syntax: server [ port ]
    
     * *
    
     * * port - protocol port number to use
    
     * *
    
     * * Note: The port argument is optional. If no port is specified,
    
     * * the server uses the default given by PROTOPORT.
    
     * *
    
     * *------------------------------------------------------------------------
    
     * */
    
    main(argc, argv)
    
    	int argc;
    
    	char *argv[];
    
    {
    
    	struct hostent *ptrh; /* pointer to a host table entry */
    
    	struct protoent *ptrp; /* pointer to a protocol table entry */
    
    	struct sockaddr_in sad; /* structure to hold server.s address */
    
    	struct sockaddr_in cad; /* structure to hold client.s address */
    
    	int sd, sd2; /* socket descriptors */
    
    	int port; /* protocol port number */
    
    	int alen; /* length of address */
    
    	char buf_recv[1000],buf_send[1000]; /* buffer for string the server sends */
    
    	char file_buffer[10000],f_buffer[1000];
    
    	int n;
    
    	FILE *fp;
    
    	
    
    #ifdef WIN32
    
    	WSADATA wsaData;
    
    	WSAStartup(0x0101, &wsaData);
    
    #endif
    
    	memset((char *)&sad,0,sizeof(sad)); /* clear sockaddr structure */
    
    	sad.sin_family = AF_INET; /* set family to Internet */
    
    	sad.sin_addr.s_addr = INADDR_ANY; /* set the local IP address */
    
    	/* Check command-line argument for protocol port and extract */
    
    	/* port number if one is specified. Otherwise, use the default */
    
    	/* port value given by constant PROTOPORT */
    
    	if (argc > 1) { /* if argument specified */
    
    		port = atoi(argv[1]); /* convert argument to binary */
    
    	} else {
    
    		port = PROTOPORT; /* use default port number */
    
    	}
    
    	if (port > 0) /* test for illegal value */
    
    		sad.sin_port = htons((u_short)port);
    
    	else { /* print error message and exit */
    
    		fprintf(stderr,"bad port number &#37;s\n",argv[1]);
    
    		exit(1);
    
    	}
    
    	/* Map TCP transport protocol name to protocol number */
    
    	if ( ((int)(ptrp = getprotobyname("tcp"))) == 0) {
    
    		fprintf(stderr, "cannot map \"tcp\" to protocol number");
    
    		exit(1);
    
    	}
    
    	/* Create a socket */
    
    	sd = socket(PF_INET, SOCK_STREAM, ptrp->p_proto);
    
    	if (sd < 0) {
    
    		fprintf(stderr, "socket creation failed\n");
    
    		exit(1);
    
    	}
    
    	/* Bind a local address to the socket */
    
    	if (bind(sd, (struct sockaddr *)&sad, sizeof(sad)) < 0) {
    
    		fprintf(stderr,"bind failed\n");
    
    		exit(1);
    
    	}
    
    	/* Specify size of request queue */
    
    	if (listen(sd, QLEN) < 0) {
    
    		fprintf(stderr,"listen failed\n");
    
    		exit(1);
    
    	}
    
    	/* Main server loop - accept and handle requests */
    
    	//while (1) {
    
    		alen = sizeof(cad);
    
    		if ( (sd2=accept(sd, (struct sockaddr *)&cad, &alen)) < 0) {
    
    			fprintf(stderr, "accept failed\n");
    
    			exit(1);
    
    		}
    
    		
    
    		sprintf(buf_send,"Please enter the file name: ");
    
    
    
    		send(sd2,buf_send,strlen(buf_send),0);
    
    		n=recv(sd2,buf_recv,1000,0);
    
    		buf_recv[n]='\0';
    
    		printf("%s\n",buf_recv);
    
    		fflush(stdout);
    
    
    
    		if((fp = fopen(buf_recv,"r"))==NULL)
    
    			{
    
    			sprintf(buf_send,"File could not be found!!!");
    
    			exit(0);
    
    			}
    
    		else
    
    			sprintf(buf_send,"File found!!!\n");
    
    		
    
    		send(sd2,buf_send,strlen(buf_send),0);
    
    		n=recv(sd2,buf_recv,1000,0);
    		printf("%s",buf_recv);
    
    		fflush(stdout);
    
    
    		while(!feof(fp))
    
    		{
    			fgets(f_buffer,1000,fp);
    			if (feof(fp))
    			break;
    			strcat(file_buffer,f_buffer);
    
    		}
    
    		fclose(fp);
    
    		send(sd2,file_buffer,strlen(file_buffer),0);
    
    		closesocket(sd2);
    
    	//}
    
    		//closesocket(sd);
    
    		exit(0);
    
    	
    
    }

    client.c

    Code:
    /* client.c - code for example client program that uses TCP */
    
    #ifndef unix
    
    #define WIN32
    
    #include <windows.h>
    
    #include <winsock.h>
    
    #else
    
    #define closesocket close
    
    #include <sys/types.h>
    
    #include <sys/socket.h>
    
    #include <netinet/in.h>
    
    #include <arpa/inet.h>
    
    #include <netdb.h>
    
    #endif
    
    #include <stdio.h>
    
    #include <string.h>
    
    #define PROTOPORT 5193 /* default protocol port number */
    
    extern int errno;
    
    char localhost[] = "localhost"; /* default host name */
    
    /*------------------------------------------------------------------------
    
     * * Program: client
    
     * *
    
     * * Purpose: allocate a socket, connect to a server
    
     * * Syntax: client [ host [port] ]
    
     * *
    
     * * host - name of a computer on which server is executing
    
     * * port - protocol port number server is using
    
     * *
    
     * * Note: Both arguments are optional. If no host name is specified,
    
     * * the client uses "localhost"; if no protocol port is
    
     * * specified, the client uses the default given by PROTOPORT.
    
     * *
    
     * *------------------------------------------------------------------------
    
     * */
    
    main(argc, argv)
    
    	int argc;
    
    	char *argv[];
    
    {
    
    	struct hostent *ptrh; /* pointer to a host table entry */
    
    	struct protoent *ptrp; /* pointer to a protocol table entry */
    
    	struct sockaddr_in sad; /* structure to hold an IP address */
    
    	int sd; /* socket descriptor */
    
    	int port; /* protocol port number */
    
    	char *host; /* pointer to host name */
    
    	int n; /* number of characters read */
    
    	char buf_recv[1000],buf_send[100]; /* buffer for data from the server */
    
    	char *filename;
    
    	char file_buffer[10000];
    
    	FILE *fp;
    
    #ifdef WIN32
    
    	WSADATA wsaData;
    
    	WSAStartup(0x0101, &wsaData);
    
    #endif
    
    	memset((char *)&sad,0,sizeof(sad)); /* clear sockaddr structure */
    
    	sad.sin_family = AF_INET; /* set family to Internet */
    
    	/* Check command-line argument for protocol port and extract */
    
    	/* port number if one is specified. Otherwise, use the default */
    
    	/* port value given by constant PROTOPORT */
    
    	if (argc > 2) { /* if protocol port specified */
    
    		port = atoi(argv[2]); /* convert to binary */
    
    	} else {
    
    		port = PROTOPORT; /* use default port number */
    
    	}
    
    	if (port > 0) /* test for legal value */
    
    		sad.sin_port = htons((u_short)port);
    
    	else { /* print error message and exit */
    
    		fprintf(stderr,"bad port number %s\n",argv[2]);
    
    		exit(1);
    
    	}
    
    	/* Check host argument and assign host name. */
    
    	if (argc > 1) {
    
    		host = argv[1]; /* if host argument specified */
    
    	} else {
    
    		host = localhost;
    
    	}
    
    	/* Convert host name to equivalent IP address and copy to sad. */
    
    	ptrh = gethostbyname(host);
    
    	if ( ((char *)ptrh) == NULL ) {
    
    		fprintf(stderr,"invalid host: %s\n", host);
    
    		exit(1);
    
    	}
    
    	memcpy(&sad.sin_addr, ptrh->h_addr, ptrh->h_length);
    
    	/* Map TCP transport protocol name to protocol number. */
    
    	if ( ((int)(ptrp = getprotobyname("tcp"))) == 0) {
    
    		fprintf(stderr, "cannot map \"tcp\" to protocol number");
    
    		exit(1);
    
    	}
    
    	/* Create a socket. */
    
    	sd = socket(PF_INET, SOCK_STREAM, ptrp->p_proto);
    
    	if (sd < 0) {
    
    		fprintf(stderr, "socket creation failed\n");
    
    		exit(1);
    
    	}
    
    	/* Connect the socket to the specified server. */
    
    	if (connect(sd, (struct sockaddr *)&sad, sizeof(sad)) < 0) {
    
    		fprintf(stderr,"connect failed\n");
    
    		exit(1);
    
    	}
    
    
    	n = recv(sd, buf_recv, sizeof(buf_recv), 0);
    
    	
    
    	buf_recv[n]='\0';
    
    	printf("%s",buf_recv);
    
    	scanf("%s",buf_send);
    
    	send(sd,buf_send,strlen(buf_send),0);
    
    	n = recv(sd, buf_recv, sizeof(buf_recv), 0);
    
    	
    
    	buf_recv[n]='\0';
    
    	printf("%s",buf_recv);
    
    	fflush(stdout);
    	
    	sprintf(buf_send,"Client acknowledges, Sending file now.\n");
    	send(sd,buf_send, strlen(buf_send),0);
    
    	
    
    	n=recv(sd, file_buffer, sizeof(file_buffer), 0);
    
    	file_buffer[n]='\0';
    
    	//printf("%s %d\n",file_buffer,n);
    
    	fflush(stdout);
    
    	fp = fopen("DOWNLOADED.TXT","w");
    
    	fputs(file_buffer,fp);
    	fclose(fp);
    
    	closesocket(sd);
    
    	/* Terminate the client program gracefully. */
    
    	exit(0);
    
    }
    Last edited by jakemott; 10-06-2008 at 02:04 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Can someome help me with a program please?
    By WinterInChicago in forum C++ Programming
    Replies: 3
    Last Post: 09-21-2006, 10:58 PM
  2. I need some help with my program please.
    By agentxx04 in forum C Programming
    Replies: 9
    Last Post: 09-26-2004, 07:51 AM
  3. How can I run a small ftp script from C program
    By bazeemuddin in forum A Brief History of Cprogramming.com
    Replies: 1
    Last Post: 07-01-2003, 05:04 PM
  4. My program, anyhelp
    By @licomb in forum C Programming
    Replies: 14
    Last Post: 08-14-2001, 10:04 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21