使用TCP网络编程实现cp操作:
#include<stdio.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <arpa/inet.h>
#include <fcntl.h>
int main(){
int ret=-1;
int sockfd=-1;
int connfd=-1;
//创建套接字
sockfd=socket(AF_INET,SOCK_STREAM,0);//使用IPv4地址(AF_INET)、TCP协议(SOCK_STREAM)
if(-1==sockfd){
perror("socket:");
return -1;
}
/*绑定套接字*/
struct sockaddr_in addr;
addr.sin_family=AF_INET;//地址族
addr.sin_port=htons(8888);//设置端口
addr.sin_addr.s_addr=inet_addr("0.0.0.0");//0.0.0.0直动获取主机ip
ret=bind(sockfd,&addr,sizeof(addr));
if(-1==ret){
perror("bing:");
return -1;
}
/*设置监听队列*/
ret=listen(sockfd,3);
if(-1==ret){
perror("listen:");
close(sockfd);
return -1;
}
/*被动等待连接*/
connfd=accept(sockfd,NULL,NULL);
if(connfd==-1){
perror("accept:");
close(sockfd);
return 0;
}
else{
printf("connected a client\n");
while(1){
char buf[20]={0};
char aimFileName[20]={0};
char fileData[50]={0};
printf("在客户端输入目标文件路径\n");
/*接收客户端命令*/
read(connfd,buf,sizeof(buf));
printf("cilent:%s\n",buf);
printf("在客户端输入复制到在文件路径:\n");
read(connfd,aimFileName,sizeof(aimFileName));
printf("cileny:%s\n",aimFileName);
int fd=open(aimFileName,O_RDONLY);
if(fd!=-1){
printf("该文件在当前目录下已存在,确定复制请按1,其他键位退出\n");
int ans;
scanf("%d",&ans);
if(ans==1){
int aimFd=open(aimFileName,O_WRONLY|O_CREAT,0666);
if(aimFd==-1){
perror("open aim file:");
return -1;
}
int firstFd=open(buf,O_RDONLY);
if(firstFd==-1){
perror("first file open:");
return -1;
}
int ret2=read(firstFd,fileData,48);
int ret3=write(aimFd,fileData,48);
if(ret2==-1){
perror("read:");
close(firstFd);
return -1;
}
if(ret3==-1){
perror("write:");
close(aimFd);
return -1;
}
char temp[]="文件复制成功!";
printf("%s\n",temp);
write(connfd,temp,sizeof(temp));
close(firstFd);
close(aimFd);
}
else{
return 0;
}
}
else{
int aimFd=open(aimFileName,O_WRONLY|O_CREAT,0666);
if(aimFd==-1){
perror("open aim file:");
return -1;
}
int firstFd=open(buf,O_RDONLY);
if(firstFd==-1){
perror("first file open:");
return -1;
}
int ret2=read(firstFd,fileData,48);
int ret3=write(aimFd,fileData,48);
if(ret2==-1){
perror("read:");
close(firstFd);
return -1;
}
if(ret3==-1){
perror("write:");
close(aimFd);
return -1;
}
char temp[]="文件复制成功!";
printf("%s\n",temp);
write(connfd,temp,sizeof(temp));
close(firstFd);
close(aimFd);
}
}
}
return 0;
}
C语言TCP网络编程--实现cp操作
最新推荐文章于 2024-05-04 15:01:52 发布