📄 网络.c
字号:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<malloc.h>
#define max_ip_data 2048
#define max_varible_head 40
#define varible_head ip_data.Varible_head
#define data ip_data.Data
struct ip_head
{
char ver_head_length;
char ser_type;
int total_len;
int iden;
int flag_offset;
char survival_time;
char protocol;
int head_check;
long source_addr;
long dest_addr;
union
{
char Varible_head[max_varible_head]; //optional portion,in this program i set it null
char Data[max_ip_data];
}ip_data;
char *data_start;
};
struct ip_head head;
FILE *fp,*fp1;
int send_data(struct ip_head *ip,long s,long d,int var)
{
int count,i;
if(var)
{
for(i=0;i<var;i++)
ip->varible_head[i]=0;
ip->ver_head_length=(char)(0x40+20+(char)var);
ip->data_start=ip->data+var;
}
else
{
ip->ver_head_length=(char)(0x40+20);
ip->data_start=ip->data;
}
ip->ser_type=(char)0x51;
ip->iden=0; //NULL
ip->survival_time=30; //30 seconds,no use in the program
ip->protocol=0; //NULL
ip->head_check=0; //not realizing
ip->source_addr=s;
ip->dest_addr=d;
count=strlen(fgets(ip->data_start,max_ip_data-var,fp));
ip->flag_offset=count%8+(count==(count/8)*8 ? 0:1);
if(count==max_ip_data-var-1)
ip->flag_offset=ip->flag_offset|0x2000;
ip->total_len=count; //the total_len is this ip datagram length,not all,for it is some difficult to realize
return count;
}
int recevie_data(struct ip_head *ip,long d)
{
if(ip->dest_addr!=d) return 0;
return 1;
}
int send_pro(long s,long d)
{
int t;
t=send_data(&head,s,d,0);
return t;
}
int rece_pro(struct ip_head *ip,long d,char *ver_head,int *total,long *s)
{
int t;
t=recevie_data(&head,d);
if(!t)return -1; //error
*ver_head=ip->ver_head_length;
*total+=ip->total_len;
*s=ip->source_addr;
fputs(ip->data_start,fp1);
if(ip->flag_offset&0x2000&&!(ip->flag_offset&0x4000)) return 1; //have more data
else return 0; //finish transfering data
}
void main(void)
{
char *p2="192.168.1.6",*p3="192.168.2.10";
char ver_head;
long sour=192<<12+168<<8+1<<4+6;
long dest=192<<12+168<<8+2<<4+10;
long s;
int tt,count,total=0;
tt=0;
if((fp=fopen("send.txt","r"))==NULL)
{
printf("can't read\n");
exit(1);
}
if((fp1=fopen("receive_data.txt","w"))==NULL)
{
printf("can't write");
exit(1);
}
while(1)
{
count=send_pro(sour,dest);
tt+=count;
if((rece_pro(&head,dest,&ver_head,&total,&s))!=1)
break;
}
fclose(fp);
fclose(fp1);
printf("\nthe source address:");
printf("%s",p2);
printf("\nthe destination address:");
printf("%s",p3);
printf("\nversion:");
printf("%d",(int)((ver_head&0xf0)>>4));
printf("\nthe ip head length:");
printf("%d",(int)(ver_head&0x0f));
printf("\nthe total data length:\n");
printf("%d",tt);
printf("\nsuccess!!:\n");
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -