#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 69 //端口号的网络字节序 1024~49151
#define IP "192.168.10.109"//windows的
#define ERR_MSG(msg)do{\
printf("line:%d",__LINE__);\
perror(msg);\
}while(0)
int main(int argc, const char *argv[])
{
//创建报式套接字socket
int cfd = socket(AF_INET,SOCK_DGRAM,0);
if(cfd < 0)
{
ERR_MSG("socket");
return -1;
}
printf("socket create success line = %d\n",__LINE__);
//
int reuse = 1;
if(setsockopt(cfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse))<0)
{
ERR_MSG("setsockopt");
return -1;
}
//给snedto函数使用
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(PORT);
sin.sin_addr.s_addr = inet_addr(IP);
//组下载协议
char buf[516] = "";
short* ptr1 = (short*)buf;
*ptr1 = htons(1); //操作码下载 read
char* ptr2 = buf+2;
strcpy(ptr2,"5.png");//要下载的文件
char *ptr3 = ptr2 + strlen(ptr2);
*ptr3 = 0;
char* ptr4 = ptr3 + 1;
strcpy(ptr4,"octet"); //模式 :二进制模式
int size = 2+strlen(ptr2)+1+strlen(ptr4)+1;
//sendto发送数据要指定发送的人
if(sendto(cfd,buf,size,0,(struct sockaddr*)&sin,sizeof(sin)) < 0)
{
ERR_MSG("sendto");
return -1;
}
printf("发送成功\n");
struct sockaddr_in r;
socklen_t len = sizeof(r);
ssize_t res = 0;
int fd = open("./copy.png",O_WRONLY|O_CREAT|O_TRUNC,0775);
if(fd < 0)
{
ERR_MSG("open");
}
while(1)
{
bzero(buf,sizeof(buf));
res = recvfrom(cfd,buf,sizeof(buf),0,(struct sockaddr*)&r,&len);
if(res < 0)
{
ERR_MSG("recvfrom");
return -1;
}
short *s1 = (short*)buf;
short a = ntohs(*s1);//把操作码拿出来作判断
short* s2 = s1+1;
short b = ntohs(*s2);//如果错了 才走
char* s3 = (char*)(s2+1);//
if(5 == a)
{
printf("操作码data错误\n");
printf("差错码:%d\n",b);
printf("差错信息:%s\n",s3);
ERR_MSG("recvfrom");
return -1;
}
write(fd,s3,res-4);
*s1 = htons(4); //操作码变成4(ASK)
bzero(s3,512);
if(sendto(cfd,buf,sizeof(buf),0,(struct sockaddr*)&r,len) < 0)
{
ERR_MSG("sendto");
return -1;
}
if(res < 516)
{
printf("speak over \n");
break;
}
}
//关闭套接字
close(cfd);
return 0;
}
项目:基于UDP的tftp客户端(下载)
于 2023-05-17 20:04:35 首次发布