/*
* filename: client.c
* DESC: the client endpoint of the UDP sending files program
* Author: linjian < lin.jian1986@gmail.com >
* Date: 2008/10/28
*/
#include <unistd.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <netdb.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 8003
#define BUF_SIZE 512
#define err_quit( MESSAGE ) \
perror( MESSAGE ), \
exit ( EXIT_FAILURE )
/*
* @name: the filename
* @sockfd: the file desc
* @addr: the server's address
* DESC: the client endpoints send the filename to the server endpoint
*/
void client_send_filename( const char *name, int sockfd, struct sockaddr_in addr )
{
int addr_len = sizeof(addr );
if ( sendto(sockfd, name, strlen(name), 0, (struct sockaddr *)&addr, addr_len) < 0 )
err_quit( "sendto failed" );
}
/*
* @name: the filename
* @sockfd: the file desc
* @addr: the server's address
* DESC: the client endpoints send the file to the server endpoint
*/
void client_send_file( const char *name, int sockfd, struct sockaddr_in addr )
{
int fd;
int addr_len;
int num_bytes;
char buffer[ BUF_SIZE ];
if ( (fd = open(name, O_RDONLY)) < 0 )
err_quit( "open failed" );
addr_len = sizeof( addr );
do {
num_bytes = read(fd, buffer, BUF_SIZE);
sendto( sockfd, buffer, num_bytes, 0, (struct sockaddr *)&addr, addr_len );
} while ( num_bytes > 0 );
fputs( "Done\n", stdout );
close( fd );
}
/*
* @result: get the filename
* @name; the file which will be send
* DESC: get the filename
*/
void get_filename( char result[], char name[] )
{
char *ptr = name;
char *temp = ptr;
char *substr = "/";
ptr = strstr(name, substr);
if ( ptr != NULL )
temp = ptr;
while ( ptr ) {
ptr = strstr( ptr + 1, substr );
if ( ptr != NULL )
temp = ptr;
}
strcpy( result, temp + 1);
}
int main( int argc, char *argv[] )
{
int sockfd;
char filename[ BUF_SIZE ] = { 0 };
struct sockaddr_in addr;
if ( argc != 3 ) {
printf( "usage: ./client [ip] [file]\n" );
exit ( EXIT_FAILURE );
}
if ( (sockfd = socket( AF_INET, SOCK_DGRAM, 0 )) < 0 )
err_quit( "socket failed" );
addr.sin_family = AF_INET;
addr.sin_port = htons( PORT );
addr.sin_addr.s_addr = inet_addr( argv[1] );
bzero( &(addr.sin_zero), 8 );
get_filename( filename, argv[2] );
client_send_filename( filename, sockfd, addr );
client_send_file( argv[2], sockfd, addr );
close( sockfd );
return 0;
}
|