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

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

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. css3阴影 box-shadow

    语法 box-shadow:X轴偏移量 y轴偏移量 [阴影模糊半径] [阴影扩展半径] [阴影颜色] [投影方式] 参数介绍: 注:inset 可以写在参数的第一个或最后一个,其它位置是无效的. 阴影 ...

  2. theano中tensor的构造方法

    import theano.tensor as T x = T.scalar('myvar') myvar = 256 print type(x),x,myvar 运行结果: <class 't ...

  3. R语言网络爬虫学习 基于rvest包

    R语言网络爬虫学习 基于rvest包 龙君蛋君:2015年3月26日 1.背景介绍: 前几天看到有人写了一篇用R爬虫的文章,感兴趣,于是自己学习了.好吧,其实我和那篇文章R语言爬虫初尝试-基于RVES ...

  4. Oracle字符编码与汉字存储长度的处理

    执行如下语句,查看汉字在数据库中所占的字节: select vsize('汉') from dual; 一般情况下,得到的结果大部分为值:2 或 3 一般linux下安装oracle数据库,默认字符编 ...

  5. 前端jQuery之文档操作

    1.文档操作内部插入 A.append(B) 吧B添加到A的后面 A.appendTo(B) 吧A添加到B的后面 A.prepend(B) 吧B添加到A的前面 A.prependTo(B) 吧A添加到 ...

  6. 3、SpringBoot+Mybatis整合------主键回填

    开发工具:STS 代码下载链接:https://github.com/theIndoorTrain/SpringBoot_Mybatis01/tree/d68efe51774fc4d96e5c6870 ...

  7. SpringMVC-实现PUT请求上传文件(转)

    因为在图片上传的时候使用的是二进制的方式上传,所以使用隐藏域进行方法转换方式失效,转方法: https://www.cnblogs.com/morethink/p/6378015.html 可是后来我 ...

  8. 远程桌面连接失败,提示CredSSP加密Oracel修正问题解决

    今天远程桌面的时候失败了,出现以下提示 于是上网找解决办法,经过测试,该方法是可行的. 首先,在控制台中输入regedit,打开注册表

  9. Percona-Tookit工具包之pt-stalk

      Preface       We have a lot of methods to diagnose problems in our system such as strace,pstack,gs ...

  10. python__基础 : 异常处理与自定义异常

    异常处理方法一般为: try: ------code----- except Exception as e: # 抛出异常之后将会执行 print(e) else: # 没有异常将会执行 print( ...