How to read/write from a tcp header bin file

I need some help on a program that I have to create for school. I don’t know exactly how to go about reading in and manipulating data from a bin file. The bin file is in the form of a tcp header and I need to:
1.Read the binary file into a struct and print the header.
2.Create a response header and write it to a new file.
3.Read the response binary file and print the header. This is what I have so far.

struct tcp
{

unsigned char sourceport[2];
unsigned char destination[2];
unsigned char sequence[4];
unsigned char ackno[4];
unsigned char other[2];
unsigned char window[2];
unsigned char checksum[2];
unsigned char urgent[2];


}my_header;



int readfile(char filename[])
{
FILE *fp;
int pointer, i;
unsigned char buffer[20];
fp = fopen(filename, "r");

if(!fp)
{
    return 1;
}

fread(&my_header, sizeof(my_header), 1, fp);
i = 0;
pointer = 0;

while (pointer < 2)
{
    my_header.sourceport[pointer] = buffer[pointer];
    pointer++;
}

while (pointer < 4)
{
    my_header.destination[pointer - 2] = buffer[pointer];
    pointer++;
}

while(pointer < 8)
{
    my_header.sequence[pointer - 4] = buffer[pointer];
    pointer++;
}

while(pointer < 12)
{
    my_header.ackno[pointer - 8] = buffer[pointer];
    pointer++;
}
while(pointer < 14)
{
    my_header.other[pointer - 12] = buffer[pointer];
    pointer++;
}
while(pointer < 16)
{
    my_header.window[pointer - 14] = buffer[pointer];
    pointer++;
}
while(pointer < 18)
{
    my_header.checksum[pointer - 16] = buffer[pointer];
    pointer++;
}
while(pointer < 20)
{
    my_header.urgent[pointer - 18] = buffer[pointer];
    pointer++;
}


fclose(fp);



return 0;
}







int main(int argc, char* argv)
{

int check;
unsigned char swap[2];

check = readfile("test.bin");

/* Checking for file to read */
if(check == 0)
{
    printf("File successfully readn");
}

/* If file is not found */
if(check == 1)
{
    printf("Cannot open/find file.n");
}

strcpy(swap,my_header.sourceport);
strcpy(my_header.sourceport, my_header.destination);
strcpy(my_header.destination, swap);


writefile("test.bin");




return 0;

}


Source: c#

Leave a Reply