Pages

Saturday, December 24, 2016

Networking - UDP Header implementation

This C program generates UDP Header with following assumptions:

1. Sample data in input.txt file: ABC
2. Source Port=1100, Destination Port=1101
3. Total length=50
4. You may use your logic for Checksum calculation.


#include <stdio.h>
void main()  
{
FILE *fp1, *fp2, *fopen(); 
int src_port=1100, dest_port=1101, total_len=50,checksum=0;
char c;

fp1 = fopen( "input.txt",  "r" );       /* open for reading */ 
fp2 = fopen( "UDPHeader.txt", "w" ) ; /* open for writing */

if ( fp1 == NULL )     /* check file exist/not  */ 
{
printf("Cannot open input.txt for reading." ); 
exit(1);     /* Exit program */ 

else if ( fp2 == NULL ) 
{
printf("Cannot open UDPHeader.txt for writing."); 
exit(1);     /* Exit program */ 

else 
{
c = getc(fp1) ;
while ( c != EOF) 
{
checksum = checksum + c;
c =  getc( fp1 ) ;

fprintf(fp2,"%d,%d,%d,",src_port,dest_port,total_len);
fprintf(fp2,"%d",checksum);
printf("UDP Header created successfully in UDPHeader.txt file.");
fclose(fp1); /*close files */
fclose(fp2); 


}

Output of the program

UDP Header created successfully in UDPHeader.txt file.

Data after program execution in UDPHeader.txt file:

1100,1101,50,198
* * * * *



No comments:

Post a Comment