int main(int argc,char **argv)
{
int server_sockfd,client_sockfd;
int server_len,client_len;
struct sockaddr_in server_address;
struct sockaddr_in client_address;
char recv_buf[516] = {};
char send_buf[516] = {};
char recv_cmd[4] = {};
int byte;
int n = 0;
int pid,fd;
server_sockfd
= socket(AF_INET,SOCK_DGRAM,0);
bzero(&server_address,sizeof(server_address));
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = inet_addr("192.168.220.59");
//我的PC机IP地址
server_address.sin_port = htons(69);
server_len = sizeof(server_address);
bind(server_sockfd,(struct sockaddr *)&server_address,server_len);
if((byte = recvfrom(server_sockfd,recv_buf,516,0,(struct sockaddr *)&client_address,sizeof(struct sockaddr))) == -1)
{
perror("recvfrom");
exit(0);
}
//创建一个进程来分析收到的报文信息
if((pid = fork()) == 0)
{
if(recv_buf[1] == 1) //为下载文件请求
{
printf("this is a read request:\n");
if((fd = open(recv_buf[2],O_RDONLY)) < 0)
{
perror("open");
exit(0);
}
while(1)
{
recvfrom(server_sockfd,recv_cmd,4,0,(struct sockaddr *)&client_address,sizeof(struct sockaddr));
read(fd,send_buf+4,sizeof(send_buf+4));
//将文件内容读入数据区
send_buf[1] = 3;
//构造报文
if((byte = sendto(server_sockfd,send_buf,516,0,(struct sockaddr *)&client_address,sizeof(struct sockaddr))) == 516)
{
sendto(server_sockfd,send_buf,4,0,(struct sockaddr *)&client_address,sizeof(struct sockaddr));
send_buf[3]++;
}
//TFTP每次发送512个字节,附带四个字节的报文信息,小于516时就代表文件传输完毕
else
exit(0);
}
}
if (recv_buf[1] == 2) //为上传文件请求
{
printf("this is a write request:\n");
if((fd = open(recv_buf[2],O_RDWR|O_CREAT)) < 0)
{
perror("open");
exit(0);
}
while(1)
{
recvfrom(server_sockfd,recv_cmd,4,0,(struct sockaddr *)&client_address,sizeof(struct sockaddr));
recvfrom(server_sockfd,recv_buf,512,0,(struct sockaddr *)&client_address,sizeof(struct sockaddr));
write(fd,send_buf+4,sizeof(send_buf+4));
send_buf[1] = 3;
if((byte = sendto(server_sockfd,send_buf,516,0,(struct sockaddr *)&client_address,sizeof(struct sockaddr))) == 516)
{
sendto(server_sockfd,send_buf,4,0,(struct sockaddr *)&client_address,sizeof(struct sockaddr));
send_buf[3]++;
}
else
exit(0);
}
}
close(fd);
}
else
return 0;
}
|