题目ftp云盘,代码编写分为客户端,服务端,配置文件
通过TCP协议,利用套接字socket具体实现。
实现功能分为客户端(lls,lpwd,lcd),服务端(ls,cd,pwd,)以及双方文件交互功能(get,put)
此为ftp云盘服务端
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include<stdio.h>
#include<string.h>
#include"msg.h"
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
//处理接收到的命令,通过配置文件中的宏定义返回相应int值
int handler_cmd(char *cmd)
{
int p;
if(!strcmp("ls",cmd)) return LS;
if(!strcmp("pwd",cmd)) return PWD;
if(!strcmp("quit",cmd)) return QUIT;
if(strstr(cmd,"cd") != NULL) return CD;
if(strstr(cmd,"put") != NULL) return PUT;
if(strstr(cmd,"get") != NULL) return GET;
return -1;
}
//cd put get命令需要分割字符串,获取第二个字符即相应文件
char *hand_message(char *cmd)
{
char *p;
p = strtok(cmd," ");
p = strtok(NULL," ");
return p;
}
//处理命令,根据返回值处理实际命令
void msg_server(struct Msg msg,int fd)
{
printf("cmd:%s\n",msg.data);
char dataBuf[4096] = {0};
char *file = NULL;
int ret;
int p_fd;
FILE *r;
ret = handler_cmd(msg.data);
switch(ret){
case LS:
case PWD:
r = popen(msg.data,"r");
fread(msg.data,sizeof(msg.data),1,r);
write(fd,&msg,sizeof(msg));
break;
case CD:{
char *dir = hand_message(msg.data);
if(access(dir,F_OK)){
printf("no this file!\n");
strcpy(msg.data,"this file no exit\n");
write(fd,&msg,sizeof(msg));
exit(-1);
}
chdir(dir);
break;
}
case PUT:
p_fd = open(hand_message(msg.data),O_RDWR|O_CREAT,0600);
write(p_fd,msg.dataBuf,strlen(msg.dataBuf));
break;
case GET:
file = hand_message(msg.data);
if(access(file,F_OK)){
strcpy(msg.data,"no this file!\n");
write(fd,&msg,sizeof(msg));
}else if(access(file,F_OK) == -1){
perror("access");
}else{
int f_fd = open(file,O_RDWR);
read(f_fd,dataBuf,sizeof(dataBuf));
close(f_fd);
strcpy(msg.data,dataBuf);
write(fd,&msg,sizeof(msg));
}
break;
case QUIT:
printf("client quit...\n");
exit(0);
}
}
int main(int argc,char **argv)
{
int s_fd;
struct sockaddr_in s_addr;
struct sockaddr_in c_addr;
struct Msg msg;
int n_read;
int c_fd;
if(argc != 3){
printf("param error\n");
exit(-1);
}
s_fd = socket(AF_INET,SOCK_STREAM,0);
if(s_fd == -1){
perror("socket");
exit(-1);
}
s_addr.sin_family = AF_INET;
s_addr.sin_port = htons(atoi(argv[2]));
inet_aton(argv[1],&s_addr.sin_addr);
bind(s_fd,(struct sockaddr *)&s_addr,sizeof(struct sockaddr));
listen(s_fd,10);
printf("waiting for client come...\n");
while(1){
int clen = sizeof(struct sockaddr);
c_fd = accept(s_fd,(struct sockaddr *)&c_addr,&clen);
if(c_fd == -1){
perror("accept");
}
printf("accepted client...\t%s\n",inet_ntoa(c_addr.sin_addr));
if(fork() == 0){
while(1){
memset(&msg.data,0,sizeof(msg.data));
n_read = read(c_fd,&msg,sizeof(msg));
printf(">");
if(n_read == 0){
printf("client quit...\n");
break;
}
else if(n_read > 0){
msg_server(msg,c_fd);
}
}
}
}
close(s_fd);
close(c_fd);
return 0;
}
上接客户端
客户端
学识浅薄,希望能帮到您