这是上传文件的一个示例,可以参照自行修改成下载或者其它功能。

在上传时,需要先将文件名传到服务器端,这是采用一个结构体,包含文件名及文件名长度(可以用于校验),防止文件名乱码。

client

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
#include "wrap.h"
#define MAXLINE 1492
#define SERV_PORT 5555
#define FILE_NAME_LEN 64 struct fileInfo{
char fileName[FILE_NAME_LEN];
int len;
}; int main(int argc, char *argv[])
{
if(argc<){
perror("Usage:./a.out ip filename");
exit(-);
}
struct sockaddr_in servaddr;
char buf[MAXLINE];
int sockfd;
//char servip[]="123.206.59.137";
sockfd = Socket(AF_INET, SOCK_STREAM, );
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
inet_pton(AF_INET, argv[], &servaddr.sin_addr);
servaddr.sin_port = htons(SERV_PORT);
Connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)); struct fileInfo file_name;
memset(&file_name,,sizeof(file_name));
strncpy(file_name.fileName,argv[],strlen(argv[]));
file_name.len=strlen(argv[]);
Write(sockfd,&file_name,sizeof(file_name));
FILE *fp=fopen(argv[],"r");
if(fp==NULL){
perror("open file failed");
Close(sockfd);
exit(-);
}
printf("open file %s successed\n",argv[]);
int len=;
while ((len=fread(buf,sizeof(char),MAXLINE,fp))>) {
Write(sockfd, buf, len);
}
fclose(fp);
Close(sockfd);
return ;
}

server

#include <stdio.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include "wrap.h"
#define MAXLINE 1492
#define SERV_PORT 5555
#define FILE_NAME_LEN 64
struct fileInfo{
char fileName[FILE_NAME_LEN];
int len;
}; int main(int argc, char *argv[]){
struct sockaddr_in serveraddr;
int listenfd;
char str[INET_ADDRSTRLEN]; listenfd=Socket(AF_INET,SOCK_STREAM,);
bzero(&serveraddr,sizeof(serveraddr));
serveraddr.sin_family=AF_INET;
serveraddr.sin_addr.s_addr=htonl(INADDR_ANY);
serveraddr.sin_port=htons(SERV_PORT); Bind(listenfd,(struct sockaddr *)&serveraddr,sizeof(serveraddr));
Listen(listenfd,); while(){
struct sockaddr_in clientaddr;
socklen_t addrLen=sizeof(clientaddr);
int confd=Accept(listenfd,(struct sockaddr *)&clientaddr,&addrLen);
printf("receive file from %s at port %d\n",
inet_ntop(AF_INET,&clientaddr.sin_addr,str,sizeof(str)),
ntohs(clientaddr.sin_port)
);
int len=;
struct fileInfo file_name;
len=Read(confd,&file_name,sizeof(file_name));
if(len==){
Close(confd);
}else {
printf("file name len=%d\n",file_name.len);
printf("file name is %s\n",file_name.fileName);
}
char buf[MAXLINE];
FILE *fp=fopen(file_name.fileName,"w");
if(!fp){
perror("open file failed");
Close(confd);
Close(listenfd);
}
while((len=Read(confd,buf,MAXLINE))>){
fwrite(buf,sizeof(char),len,fp);
}
if(len==){
fclose(fp);
printf("receive file done\n");
Close(confd);
}
}
Close(listenfd);
return ;
}

wrap.c

#include "wrap.h" 

/*********************************************************************
* * Name : perr_exit
* * Description : exit the function
* * Input : the error string
* * Output :
* * Return :
* * Others : by jzk 2009.12.02
* **********************************************************************/
void perr_exit(const char *s)
{
perror(s);
exit();
} /*********************************************************************
* * Name : Accept
* * Description : accept a connection on a socket
* * Input : fd---a socket that has been created
* * sa---a pointer to a sockaddr structure
* * salenptr---actual size of the peer address
* * Output :
* * Return : the descriptor for the accepted socket
* * Others : by jzk 2009.12.02
* **********************************************************************/
int Accept(int fd, struct sockaddr *sa, socklen_t *salenptr)
{
int n; again:
if((n = accept(fd, sa, salenptr)) < ) {
if((ECONNABORTED == errno) || (EINTR == errno))
goto again;
else
perr_exit("accept error");
} return n;
} /*********************************************************************
* * Name : Bind
* * Description : bind a name to a socket
* * Input : fd---a socket that has been created
* * sa---a pointer to a sockaddr structure
* * salen---the size of the address structure
* * Output :
* * Return :
* * Others : by jzk 2009.12.02
* **********************************************************************/
void Bind(int fd, const struct sockaddr *sa, socklen_t salen)
{
if(bind(fd, sa, salen) < )
perr_exit("bind error");
} /*********************************************************************
* * Name : Connect
* * Description : initiate a connection on a socket
* * Input : fd---a socket that has been created
* * sa---a pointer to a sockaddr structure
* * salen---the size of the address structure
* * Output :
* * Return :
* * Others : by jzk 2009.12.02
* **********************************************************************/
void Connect(int fd, const struct sockaddr *sa, socklen_t salen)
{
if(connect(fd, sa, salen) < )
perr_exit("connect error");
} /*********************************************************************
* * Name : Listen
* * Description : listen for connections on a socket
* * Input : fd---a socket that has been created
* * backlog---the maximum length to the queue of
* * pending connections
* * Output :
* * Return :
* * Others : by jzk 2009.12.02
* **********************************************************************/
void Listen(int fd, int backlog)
{
if(listen(fd, backlog) < )
perr_exit("listen error");
} /*********************************************************************
* * Name : Socket
* * Description : create an endpoint for communication
* * Input : family---a communication domain
* * type---the communication semantics
* * protocol---a particular protocol for the socket
* * Output :
* * Return : return a descriptor of the socket
* * Others : by jzk 2009.12.02
* **********************************************************************/
int Socket(int family, int type, int protocol)
{
int n; if((n = socket(family, type, protocol)) < )
perr_exit("socket error");
return n;
} /*********************************************************************
* * Name : Read
* * Description : read from a file descriptor
* * Input : fd---a socket that has been created
* * ptr---the buffer which storage the bytes
* * nbytes---the number of bytes read
* * Output :
* * Return : return the number of bytes read
* * Others : by jzk 2009.12.02
* **********************************************************************/
ssize_t Read(int fd, void *ptr, size_t nbytes)
{
ssize_t n; again:
if((n = read(fd, ptr, nbytes)) == -) {
if(EINTR == errno)
goto again;
else
return -;
} return n;
} /*********************************************************************
* * Name : Write
* * Description : write to a file descriptor
* * Input : fd---a socket that has been created
* * ptr---buffer of the bytes
* * nbytes---the number of bytes written
* * Output :
* * Return : return the number of bytes written
* * Others : by jzk 2009.12.02
* **********************************************************************/
ssize_t Write(int fd, const void *ptr, size_t nbytes)
{
ssize_t n; again:
if((n = write(fd, ptr, nbytes)) == -) {
if(EINTR == errno)
goto again;
else
return -;
} return n;
} /*********************************************************************
* * Name : Close
* * Description : close a file descriptor
* * Input : fd---a socket that has been created
* * Output :
* * Return :
* * Others : by jzk 2009.12.02
* **********************************************************************/
void Close(int fd)
{
if(close(fd) == -)
perr_exit("close error");
} /*********************************************************************
* * Name : Readn
* * Description : read from a file descriptor,
* * make sure read the enough bytes
* * Input : fd---a socket that has been created
* * ptr---the buffer which storage the bytes
* * nbytes---the number of bytes read
* * Output :
* * Return : return the number of bytes read
* * Others : by jzk 2009.12.02
* **********************************************************************/
ssize_t Readn(int fd, void *vptr, size_t nbytes)
{
size_t nleft;
size_t nread;
char *ptr; ptr = vptr;
nleft = nbytes; while(nleft > ) {
if((nread = read(fd, ptr, nleft)) < ) {
if(EINTR == errno)
nread = ;
else
return -;
} else if(nread == )
break; nleft -= nread;
ptr += nread;
} return (nbytes-nleft);
} /*********************************************************************
* * Name : Writen
* * Description : write to a file descriptor,
* * make sure write the enough bytes
* * Input : fd---a socket that has been created
* * ptr---the buffer which storage the bytes
* * nbytes---the number of bytes read
* * Output :
* * Return : return the number of bytes read
* * Others : by jzk 2009.12.02
* **********************************************************************/
ssize_t Writen(int fd, const void *vptr, size_t nbytes)
{
size_t nleft;
size_t nwritten;
const char *ptr; ptr = vptr;
nleft = nbytes; while(nleft > ) {
if((nwritten = write(fd, ptr, nleft)) <= ) {
if(nwritten < && EINTR == errno)
nwritten = ;
else
return -;
} nleft -= nwritten;
ptr += nwritten;
} return nbytes;
} static ssize_t my_read(int fd,char *ptr)
{
static int read_cnt;
static char *read_ptr;
static char read_buf[]; if(read_cnt<=){
again:
if((read_cnt=read(fd,read_buf,sizeof(read_buf))<)){
if(errno==EINTR)
goto again;
return -;
}else if(read_cnt==)
return ;
read_ptr=read_buf;
}
read_cnt--;
*ptr=*read_ptr++;
return ;
}
size_t Read_line(int fd,void *vptr,size_t maxlen)
{
ssize_t n,rc;
char c,*ptr; ptr=vptr;
for(n=;n<maxlen;n++){
if((rc=my_read(fd,&c))==){
*ptr++=c;
if(c=='\n')
break;
}else if(rc==){
*ptr=;
return n-;
}else
return -;
}
*ptr=;
return n;
}

wrap.h

#ifndef WRAP_H
#define WRAP_H #include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/socket.h> void perr_exit(const char *s); int Accept(int fd, struct sockaddr *sa, socklen_t *salenptr);
void Bind(int fd, const struct sockaddr *sa, socklen_t salen);
void Connect(int fd, const struct sockaddr *sa, socklen_t salen);
void Listen(int fd, int backlog); int Socket(int family, int type, int protocol);
void Close(int fd); ssize_t Read(int fd, void *ptr, size_t nbytes);
ssize_t Write(int fd, const void *ptr, size_t nbytes); ssize_t Readn(int fd, void *vptr, size_t n);
ssize_t Writen(int fd, const void *vptr, size_t n); ssize_t Readline(int fd, void *vptr, size_t maxlen); #endif

Makefile

######################################
#
#######################################
#source file
#源文件,自动找所有.c和.cpp文件,并将目标定义为同名.o文件
SOURCE := $(wildcard *.c) $(wildcard *.cpp)
OBJS := $(patsubst %.c,%.o,$(patsubst %.cpp,%.o,$(SOURCE))) #target you can change test to what you want
#目标文件名,输入任意你想要的执行文件名
TARGET := client server
APP1 := client
APP2 := server MAINS :=$(APP1).o $(APP2).o
#compile and lib parameter
#编译参数
CC := gcc
LIBS := -lpthread -lrt
LDFLAGS :=
DEFINES :=
INCLUDE := -I.
CFLAGS := -g -Wall -O3 $(DEFINES) $(INCLUDE)
CXXFLAGS:= $(CFLAGS) -DHAVE_CONFIG_H #i think you should do anything here
#下面的基本上不需要做任何改动了
.PHONY : everything objs clean veryclean rebuild everything : $(TARGET) all : $(TARGET) objs : $(OBJS) rebuild: veryclean everything clean :
rm -fr *.so
rm -fr *.o veryclean : clean
rm -fr $(TARGET) $(APP1) :$(APP1).o $(filter-out $(MAINS), $(OBJS))
$(CC) $(CXXFLAGS) -o $@ $^ $(LDFLAGS) $(LIBS)
$(APP2) :$(APP2).o $(filter-out $(MAINS), $(OBJS))
$(CC) $(CXXFLAGS) -o $@ $^ $(LDFLAGS) $(LIBS)

linux socket c/s上传文件的更多相关文章

  1. Linux中ftp不能上传文件/目录的解决办法

    在linux中不能上传文件或文件夹最多的问题就是权限问题,但有时也不一定是权限问题了,像我就是空间不够用了,下面我来总结一些ftp不能上传文件/目录的解决办法   在排除用户组和权限等问题后,最可能引 ...

  2. windows、linux下通过ftp上传文件小脚本

    一.windows @echo off #open ip 将要上传文件的IP地址echo open IP>ftp.up #用户名echo ninic>>ftp.up #密码echo ...

  3. Linux服务器下载与上传文件

    一.图形化工具 FileZilla.SecureCRT,连接Linux服务器后直接操作 二.命令 使用终端模拟软件连接服务器后,首先安装lrzsz工具包 yum install lrzsz rz ,上 ...

  4. 【Azure 应用服务】PHP应用部署在App Service for Linux环境中,上传文件大于1MB时,遇见了413 Request Entity Too Large 错误的解决方法

    问题描述 在PHP项目部署在App Service后,上传文件如果大于1MB就会遇见 413 Request Entity Too Large 的问题. 问题解决 目前这个问题,首先需要分析应用所在的 ...

  5. linux 软连接方式实现上传文件存储目录的无缝迁移

    背景: 由于前期的磁盘空间规划与后期的业务要求不符合.原先/home被用于用户上传文件的存储目录,但是由于上传文件的逐渐增多,而原来的/home目录的空间不足,需要给/home目录进行扩容.同时各个应 ...

  6. Linux系统下定时上传文件至FTP服务器脚本

    环境:Red Hat Enterprise Linux Server release 6.4 需求:需要将Oracle数据库的定时备份上传至FTP服务器 1.干货,用户名:oracle,数据库名称:X ...

  7. “通过jumpserver远程登录linux服务器,rz上传文件速度过慢”问题的解决

    问题: windows通过jumpserver远程登录到linux服务器,使用rz上传jar包,速度太慢(10k以内). 解决方案: 思路:通过ssh直接登录远程服务器 1.secureCRT-> ...

  8. linux 系统filezilla无法上传文件 553 Could not create

    做网站过程中遇见了很多问题,解决了但是解决方法过一段时间就会遗忘,整理出来以便以后查看. 响应: 553 Could not create file.错误: 严重文件传输错误 解决方案: 一.必须将站 ...

  9. linux服务器rz命令上传文件

    1.首先,要是服务器不支持rz命令的话,需要安装执行 yum -y install lrzsz  2.再输入rz -be命令,选择需要上传的本地文件 

随机推荐

  1. 灵光一现的trick

    感觉平时会丢掉好多挺好的trick…… 图论 1.图G,固定S,T.可以将任意一条边加上权值$k(k>0)$,求最大化加权后最短路. 2.图G,固定S,T.可以将任意一条边乘以权值$k(k> ...

  2. 基于mybatis设计简单OA系统问题2

    1.<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <fm ...

  3. 统计寄存器AX中1 的个数

    ;==================================== ; 统计寄存器AX中1 的个数 DATAS segment DATAS ends CODES segment START: ...

  4. layer 点击弹出图片

    今天做东西有一个功能:在列表点击图片弹出并放大显示,使用到了layer的页面层,下边是个小demo success:function (e) { var url = e.qrcode_url; //a ...

  5. 课时68.id选择器(掌握)

    1.什么是id选择器? 作用:根据指定的id名称找到对应的标签,然后设置属性 格式: #id名称{ 属性:值; } 注意点: 1.每个html标签都有一个属性叫做id,也就是说每个标签都可以设置id ...

  6. mysql 按值排序

    order by FIELD(AuditorStatus,3,0,1,2) laravel 写法 $data = $query->orderByRaw(\DB::Raw('FIELD(Audit ...

  7. Android内购订单验证 --- nodejs实现

    主代码: function AndroidPlayVerify(inappPurchaseData, inappDataSignature) { let verify = crypto.createV ...

  8. 01 mysql 基础一 (进阶)

    mysql基础一 1.认识mysql与创建用户 01 Mysql简介 Mysql是最流行的关系型数据库管理系统之一,由瑞典MySQLAB公司开发,目前属于Oracle公司. MySQL是一种关联数据库 ...

  9. windows系统下用VScode配置远程编辑服务器文件的环境!通过Rmate方法

    虽然公司电脑win可以通过Xshell通过SSH远程连接家中内网linux服务器了,但是只能用vim编辑文件有点不爽. 于是上网查询,windows下使用vscode远程编辑服务器文件的办法.参照博文 ...

  10. C语言函数篇(四)函数的设计

    1. 函数设计的时候,如果使用到全局变量,就尽量通过参数的形式传递进来 也就是说,保持 函数 跟 外部的交互 只有 参数 和 返回值 2. 在有参数的情况下,或者有数值输入的时候,要先进行错误判断. ...