上传代码
#include <stdio.h>//客户端
#include <string.h>
#include <stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<head.h>
#define PORT 69
#define IP "192.168.124.57"
int main(int argc, const char *argv[])
{//创建报式套接字int sfd=socket(AF_INET,SOCK_DGRAM,0);if(sfd<0){perror("socket");return -1;}printf("sfd=%d\n",sfd);//绑定客户端的地址信息结构体到套接字上--->非必须绑定//若不绑定 则操作系统会给客户端绑定运行主机的ip和随机接口////填充服务器的地址信息结构体 给sendto函数使用//要发给谁就填谁的地址信息struct sockaddr_in sin;sin.sin_family=AF_INET;//必须填AF_INETsin.sin_port=htons(PORT);//端口号 1024-49151sin.sin_addr.s_addr=inet_addr(IP);//服务器ip地址char buf[516]="";char ack[4]="";ssize_t res;int fp;short *p=(short*)buf;//操作码*p=htons(2); char *p1=buf+2;strcpy(p1,"1.c");char *p2=p1+strlen(p1)+1;strcpy(p2,"octet");if(sendto(sfd,buf,sizeof(buf),0,(struct sockaddr*)&sin,sizeof(sin))<0)//申请上传请求{perror("sendto");return -1;}//打开文件fp=open("./01_udpser.c",O_RDONLY);struct sockaddr_in cin; //存储接收到的数据socklen_t addrlen=sizeof(cin);while(1){res=0;printf("__%d__\n",__LINE__);socklen_t addrlen=sizeof(cin);bzero(buf,sizeof(buf));res=recvfrom(sfd,ack,sizeof(ack),0,(struct sockaddr*)&cin,&addrlen);printf("__%d__\n",__LINE__);if(res<0){perror("recvfrom");return -1; }// sin.sin_port=cin.sin_port;//提取ack的快编号 封装buf包//ackprintf("%d %d %d %d\n",ack[0],ack[1],ack[2],ack[3]);short *p3=(short*)buf;*p3=htons(3);short *p4=(short*)(buf+2);static short b=1;*p4=htons(b);b++;//buf[3] = ack[3] + 1;printf("%d\n",buf[3]);res=read(fp,buf+4,sizeof(buf)-4);printf("%ld\n",res);if(res<0){perror("read");return -1;}// printf("%s\n",buf+4);if(sendto(sfd,buf,sizeof(buf),0,(struct sockaddr*)&cin,addrlen) > 0)//发送数据包printf("%d\n",100);if(res<512){break;}}close(fp);close(sfd);return 0;
}