这个项目是在Linux内通过套接字网络和链表实现账号密码登陆,ls指令显示文件名,ls也可以加参数如 ls -l,get指令实现从服务端下载文件到客户端,put指令实现从客户端发送文件给服务端,cd指令实现文件夹切换,hist指令实现查看历史输入指令,当输入quit时退出
话不多说,上我一个礼拜的干货
server.c******服务端
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include "log.h"
#include "msg.h"
#include "utils.h"
#include <unistd.h>
#include <signal.h>
int g_running;
void handle_cmd(struct Msg *incmd, struct Msg *outcmd) {
FILE *fp = NULL;
int ret;
outcmd->cmd = incmd->cmd;
switch (incmd->cmd) {
case FTP_CMD_LS:
fp = popen(incmd->args, "r");
if (NULL != fp) {
ret = fread(outcmd->data, 1, sizeof(outcmd->data), fp);
log_write("ls fread ret %d, eof % d, data % s\n ", ret,
feof(fp), outcmd->data);
pclose(fp);
}
break;
default:
break;
}
}
void handle_cmd2(struct Msg *incmd, struct Msg *outcmd) {
static struct Linklist *hist = NULL;
log_write("cmd %d, args %s\n", incmd->cmd, incmd->args);
outcmd->cmd = incmd->cmd;
// HIST
listInsert(&hist, incmd->args);
if (FTP_CMD_LS == incmd->cmd) {
FILE *fp = popen(incmd->args, "r");
if (fp != NULL) {
int ret = fread(outcmd->data, 1, sizeof(outcmd->data), fp);
log_write("ls fread ret %d, %s", ret, outcmd->data);
pclose(fp);
}
} else if (FTP_CMD_HIST == incmd->cmd) {
listGetcmd(hist, outcmd->data);
} else if (FTP_CMD_GET == incmd->cmd) {
char filename[32];
if ((splitString(incmd->args, filename)) < 0) {
outcmd->cmd = FTP_CMD_ERROR;
log_write("filename isnot exist\n");
return;
}
outcmd->data_length = getLength(filename);
if (outcmd->data_length == -1 || outcmd->data_length > 5000) {
log_write("data length is too long or open failure\n");
return;
}
FILE *fp = fopen(filename, "r");
if (fp != NULL) {
int ret = fread(outcmd->data, 1, outcmd->data_length, fp);
log_write("fread ret %d, eof:%d\n", ret, feof(fp));
fclose(fp);
}
} else if (FTP_CMD_PUT == incmd->cmd) {
char filename[32];
filename[0] = '+';
splitString(incmd->args, &filename[1]);
FILE *fp = fopen(filename, "w");
if (fp != NULL) {
int ret = fwrite(incmd->data, 1, incmd->data_length, fp);
log_write("fwrite ret %d, filename %s, data_length %d", ret,