C语言实现FTP(C/S)协议(ls命令和download命令)用两个端口实现(命令端口和数据端口)

Server:


#include <stdio.h>

#include <stdlib.h>

#include <sys/socket.h>

#include <unistd.h>//sleep();

#include <netinet/in.h>

#include <arpa/inet.h>

#include <string.h>

#include<dirent.h>

#include <fcntl.h>

#define SERVER_NET_PORT 4396

#define TRANSPORT_PORT 8888

int initSocket(struct sockaddr_in * in,int sizeOfIn,int port){

    int sock;

    if ((sock = socket(AF_INET,SOCK_STREAM,0)) == -1) {

        printf("创建原始套接字出错!\n");

        exit(1);//异常退出1/-1,正常退出0

    }

    //封装地址:(为本机地址)

    in->sin_addr.s_addr = inet_addr("0.0.0.0");

    in->sin_family = AF_INET;

    in->sin_port = htons(port);

    //bind连接socket与ip:

    if (bind(sock, (struct sockaddr *)in, sizeOfIn) != 0) {

        printf("bind error!\n");

        exit(1);

    }

    

    return sock;

}

void server_ls(int sock,char * recExCmd){

    char sendBuf[1024];

    DIR * d = opendir(recExCmd);

    struct dirent * e;

    while ((e=readdir(d))) {

        if (e->d_name[0]!='.') {

//            printf("write %s\n",e->d_name);

            char a[5] = "\n";

//            write(sock, sendBuf, sizeof(sendBuf));

//            strcat(e->d_name, a);

            strcat(sendBuf, e->d_name);

            strncat(sendBuf, a, 1);

        }

    }

    if (write(sock, sendBuf, sizeof(sendBuf)) < 0) {

        printf("write error!\n");

    }else

        printf("write %s",sendBuf);

}

void serverDownload(int sock,char * recExCmd){

    int openfd;

    char readBuf[1024];

    if ((openfd=open(recExCmd, O_RDONLY)) == -1) {

        printf("open error!\n");

        close(openfd);

    }else{ //opened!

        ssize_t readLen;

        //这里用循环是因为可能缓冲区不够容纳整个文件:

        while ((readLen=read(openfd, readBuf, sizeof(readBuf))) > 0) {

            if (write(sock, readBuf, readLen)<0) {

                printf("Open file error!");

                break;

            }

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值