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;
}