Wednesday, December 22, 2010

Passport Automation System

Problem statement and SRS(Software Requirements Specification) for Passport Automation System in OOAD Lab, Anna University.

(All of the information given below are just an example created for OOAD Lab exercise and not for any other purpose. And It is just a sample, with which you can build upon.)

Download the SRS for Passport Automation System


Problem Statement


Passport Automation System is used in the effective dispatch of passport to all of the applicants. This system adopts a comprehensive approach to minimize the manual work and schedule resources, time in a cogent manner. The core of the system is to get the online registration form (with details such as name, address etc.,)  filled by the applicant whose testament is verified for its genuineness by the Passport Automation System with respect to the already existing information in the database. This forms the first and foremost step in the processing of passport application. After the first round of verification done by the system, the information is in turn forwarded to the regional administrator's (Ministry of External Affairs) office. The application is then processed manually based on the report given by the system, and any forfeiting identified can make the applicant liable to penalty as per the law. The system also provides the applicant the list of available dates for appointment to 'document verification' in the administrator's office, from which they can select one. The system forwards the necessary details to the police for its separate verification whose report is then presented to the administrator. The administrator will be provided with an option to display the current status of application to the applicant, which they can view in their online interface. After all the necessary criteria has been met, the original information is added to the database and the passport is sent to the applicant. 

Software Requirements Specification

1.0 Introduction
    Passport Automation System is an interface between the Applicant and the Authority responsible for the Issue of Passport. It aims at improving the efficiency in the Issue of Passport and reduce the complexities involved in it to the maximum possible extent.
   
    1.1 Purpose

            If the entire process of 'Issue of Passport' is done in a manual manner then it would take several months for the passport to reach the applicant. Considering the fact that the number of applicants for passport is increasing every year, an Automated System becomes essential to meet the demand. So this system uses several programming and database techniques to elucidate the work involved in this process. As this is a matter of National Security, the system has been carefully verified and validated in order to satisfy it. 

    1.2 Scope

• The System provides an online interface to the user where they can fill in their personal details and submit the necessary documents (may be by scanning).
• The authority concerned with the issue of passport can use this system to reduce his workload and process the application in a speedy manner.
• Provide a communication platform between the applicant and the administrator.
• Transfer of data between the Passport Issuing Authority and the Local Police for verification of applicant's information.
• Users/Applicants will come to know their status of application and the date in which they must subject themselves for manual document verification.

    1.3 Definitions, Acronyms and the Abbreviations       

• Administrator - Refers to the super user who is the Central Authority who has been vested with the privilege to manage the entire system. It can be any higher official in the Regional Passport Office of Ministry of External Affairs.            
• Applicant - One who wishes to obtain the Passport.
• PAS - Refers to this Passport Automation System.
• HTML - Markup Language used for creating web pages.
• J2EE – Java 2 Enterprise Edition is a programming platform and it is the partof the java platform for developing and running distributed java applications.
• HTTP - Hyper Text Transfer Protocol.
• TCP/IP – Transmission Control Protocol/Internet Protocol is the communication protocol used to connect hosts on the Internet.

    1.4 References

            IEEE Software Requirement Specification format.

    1.5 Technologies to be used

• HTML
• JSP
• Javascript
• Java
• XML
• AJAX

    1.6 Tools to be Used   

• Eclipse IDE ( Integrated Development Enivronment)
• Rational Rose tool ( for developing UML Patterns)

    1.7 Overview   

            SRS includes two sections overall description and specific requirements - Overall description will describe major role of the system components and inter-connections. Specific requirements will describe roles & functions of the actors.
               

2.0 Overall Description

    2.1 Product Perspective

            The PAS acts as an interface between the 'applicant' and the 'administrator'. This system tries to make the interface as simple as possible and at the same time not risking the security of data stored in.This minimizes the time duration in which the user receives the passport. 

    2.2 Software Interface


Front End Client - The applicant and Administrator online interface is built using JSP and HTML. The Administrators's local interface is built using Java.
Web Server - Glassfish application server(Oracle Corporation).
Back End - Oracle database.

    2.3 Hardware Interface

            The server is directly connected to the client systems. The client systems have access to the database in the server.

    2.4 System Functions

• Secure Registration of information by the Applicants.
• Schedule the applicants an appointment for manual verification of original documents.
• Panel for Passport Application Status Display by the Administrator.       
• SMS and Mail updates to the applicants by the administrator.
• Administrator can generate reports from the information and is the only authorized personnel to add the eligible application information to the database.

    2.5 User Characteristics   

• Applicant - They are the people who desires to obtain the passport and submit the information to the database.
• Administrator - He has the certain privileges to add the passport status and to approve the issue of passport. He may contain a group of persons under him to verify            
the documents and give suggestion whether or not to approve the dispatch of passport.
• Police - He is the person who upon receiving intimation from the PAS, perform a personal verification of the applicant and see if he has any criminal case against him before or at present. He has been vetoed with the power to decline an application by suggesting it to the Administrator if he finds any discrepancy with the applicant. He communicates via this PAS.

    2.6  Constraints        

• The applicants require a computer to submit their information.
• Although the security is given high importance, there is always a chance of intrusion in the web world which requires constant monitoring.
• The user has to be careful while submitting the information. Much care is required.

    2.7 Use Case Model Description       

   


    2.8  Assumptions and Dependencies


• The Applicants and Administrator must have basic knowledge of computers and English Language.
• The applicants may be required to scan the documents and send.    

      

Friday, December 17, 2010

Creating Image Maps in HTML

Image Maps

In HTML and XHTML , an image map is a list of coordinates relating to a specific image, created in order to hyperlink areas of the image to various destinations (as opposed to a normal image link, in which the entire area of the image links to a single destination). For example, a map of the world may have each country hyperlinked to further information about that country. The intention of an image map is to provide an easy way of linking various parts of an image without dividing the image into separate image files.

Advantages of using Image Maps

  • Image maps can provide an aesthetically pleasing alternative to cluttered pages. 
  • The image map allows you to use a single image to provide links to a number of different URLs. This is especially useful if you have a website with a lot of images and you do not want to slow down the loading of pages over slow connections.  
Question

Create a web page with the following using HTML
  • To embed an image map in a web page.
  • To fix the hot spots.
  • Show all the related information when the hot spots are clicked.

Solution

I will explain the use of hotspots by using the map of India.


The basic syntax of Image Map is

    <img src="...." usemap="#mapname">

    .

    .

    .

    <map name = "mapname">

    <area shape="Shape" coords="..." href="..."

    </map>

where coords represents the coordinates of the shape of the hotpsot.

By usemap we specify the name of the map we have to use.

href specifies the link that the page has to navigate when the hotspot is clicked.

Now here Shape can be any one of the following,

  1. rect
  2. poly
  3. circle
rect
 
Rectangle has four coordinates. The first specifies the top left corner, and the second the bottom right corner of the rectangle.

<area shape="rect" COORDS="0,0,9,9">

circle

circle is defined by its center coordinate and its radius.

poly

A polygon is built up by a list of coordinates. They are all connected in the order you present, and the last coordinate pair is connected to the first. This way you can build arbitrary figures. For example, <area shape=poly coords="10,50,15,20,20,50"> would specify a triangle, with edge locations (10,50), (15,20) and (20,50).

Program

Now the example that I am going to demonstrate is to create an India Map and define hotspots for each state and when a state is clicked in the map the details of the state like capital, population and tourists places would be displayed.

Download the complete source code (recommended)

I will display a sample of the program alone here, you are recommended to download the full source code and see it for yourself.








































 

    Sunday, December 12, 2010

    Anna University GPA calculator

    Hi guys, I have written a Script for an Anna University GPA Calculator in this post. I google searched and found that there is no dedicated calculator for Anna University Students. Freshers really find it difficult. So I just thought in my break I could do this and so here it goes,

    Please enter the grades in Caps

                     Grade    Credits
    Subject 1      
    Subject 2      
    Subject 3      
    Subject 4      
    Subject 5      
    Subject 6      
    Subject 7      
    Subject 8      
    Subject 9      






    However if you feel you need a software to download it to your computer, you can visit my post,

    http://vivekvenkatesh.blogspot.com/2009/12/gpa-calculator.html

    PS: You can find this script in the sidebar of this blog too....:)

    Thursday, October 28, 2010

    Generic Programming Notes

    Download notes for the fourth chapter of Programming Paradigms.

    (Prepared by Santhosh Kumar S)

    Generic Programming.docx

    Wednesday, October 20, 2010

    Single Pass Assembler in C

    Question

    To implement a single Pass assembler in C language.

    Program

    #include "stdio.h"
    #include "string.h"
    #include "stdlib.h"
    int count[20];
    void wordcount()
    {
    FILE *f3;
    f3=fopen("input.c","r");
    int word=0,i=1;
    char c;
    while((c=getc(f3))!=EOF)
    {
    if(c==' ')
    word+=1;
    if(c=='\n')
    {
    word+=1;
    count[i] = word;
    printf("\n No.of words in line %d is %d",i,word);
    i++;
    word=0;
    }
    }
    fclose(f3);
    }
    void main()
    {
    char lbl[10],mne[10],opd[10],mne1[10],opd1[10],opd2[10],val[10],adr1[10];
    int locctr,linenumber,f;
    FILE *f1,*f2,*f3,*f4;
    f1=fopen("input.c","r");
    f2=fopen("symtab.c","w+");
    f4=fopen("inter.c","w");
    printf("\n WORD COUNT OF THE PROGRAM IS :");
    wordcount();
    printf("\n Source \t Code \t Opcode \t Object code\n");
    fscanf(f1,"%s %s %x",lbl,mne,&locctr);
    linenumber=2;
    while(!feof(f1))
    {
    if(count[linenumber]==3)
    {
    fscanf(f1,"%s %s %s",lbl,mne,opd);
    fprintf(f4,"%x \t %s \t %s \t %s\n",locctr,lbl,mne,opd);
    fprintf(f2,"%x \t %s \t %s\n",locctr,lbl,opd);
    if(strcmp(mne,"RESB")==0 || strcmp(mne,"RESW")==0)
    {
    printf("%s \t %s \t 00 \t 0000\n",lbl,mne);
    }
    else
    printf("%s \t %s \t 00 \t 000%s\n",lbl,mne,opd);
    }
    if(count[linenumber]==2)
    {
    fscanf(f1,"%s %s",mne,opd);
    fprintf(f4,"%x \t %s \t %s\n",locctr,mne,opd);
    printf("%s \t %s \t",mne,opd);
    f3=fopen("opcode.c","r");
    while(!feof(f3))
    {
    fscanf(f3,"%s%s\n",mne1,opd1);
    if(strcmp(mne,mne1)==0)
    printf("%s \t",opd1);
    }
    fclose(f3);
    f=0;
    rewind(f2);
    //f2=fopen("symtab.c","r");
    while(!feof(f2))
    {
    fscanf(f2,"%s %s %s",adr1,opd2,val);
    if(strcmp(opd,opd2)==0)
    {
    printf("%s\n",adr1);
    f=1;
    }
    }
    if(f=0)
    printf("0000\n");
    }
    if(count[linenumber]==1)
    {
    fscanf(f1,"%s\n",mne);
    fprintf(f4,"%x %s\n",locctr,mne);
    }
    linenumber+=1;
    if(strcmp(mne,"WORD")==0)
    locctr+=3;
    else if(strcmp(mne,"BYTE")==0)
    locctr+=strlen(opd);
    else if(strcmp(mne,"RESW")==0)
    locctr+=3*(atoi(opd));
    else if(strcmp(mne,"RESB")==0)
    locctr+=atoi(opd);
    else
    locctr+=3;
    }
    fclose(f1);
    fclose(f2);
    fclose(f4);
    }

    Download Source Code

    Macro Processor in C

    Question

    To Implement a Macro Processor in C language.

    Program

    #include "stdio.h"
    #include "string.h"
    #include "stdlib.h"
    void main()
    {
    FILE *fp1,*fp2,*fp3,*fp4;
    char opcode[50],name[50],def[50];
    fp1=fopen("source.dat","r");
    fp2=fopen("define.dat","w");
    fp3=fopen("name.dat","w");
    fp4=fopen("out.dat","w");
    while(!feof(fp1))
    {
    fscanf(fp1,"%s",opcode);
    strcpy(name,opcode);
    fscanf(fp1,"%s",opcode);
    if(strcmp(opcode,"MACRO")==0)
    {
    fprintf(fp3,"%s\n",name);
    fprintf(fp2,"%s\n",name);
    while(strcmp(opcode,"MEND")!=0)
    {
    fprintf(fp2,"%s\n",opcode);
    fscanf(fp1,"%s",opcode);
    }
    fprintf(fp2,"MEND\n");
    }
    }
    fclose(fp1);
    fclose(fp2);
    fclose(fp3);
    fp1=fopen("source.dat","r");
    fp3=fopen("name.dat","r");
    fp2=fopen("define.dat","r");
    fscanf(fp2,"%s",def);
    while(!feof(fp1))
    {
    fscanf(fp1,"%s",opcode);
    fscanf(fp3,"%s",name);
    if(strcmp(opcode,name)==0)
    {
    fscanf(fp1,"%s",opcode);
    if(strcmp(opcode,"MACRO")==0)
    {
    while(strcmp(opcode,"MEND")!=0)
    {
    fscanf(fp1,"%s",opcode);
    }
    }
    }
    else
    {
    strcpy(name," ");
    if(strcmp(opcode,def)==0)
    {
    fscanf(fp2,"%s",def);
    if(strcmp(def,"MACRO")==0)
    fscanf(fp2,"%s",def);
    while(strcmp(def,"MEND")!=0)
    {
    fprintf(fp4,"%s\n",def);
    fscanf(fp2,"%s",def);
    }
    fscanf(fp2,"%s",def);
    }
    else if(strcmp(opcode,"END")==0)
    {
    fprintf(fp4,"END\n");
    break;
    }
    else
    {
    fprintf(fp4,"%s\n",opcode);
    }

    }
    }
    }

    Download Source Code


    source.dat

    ADDA MACRO
    CLEAR A
    ADD 05
    MEND
    SUBA MACRO
    CLEAR A
    SUB 05
    MEND
    COPY START 0
    CLEAR X
    ADDA
    SUBA
    END

    define.dat

    ADDA
    MACRO
    CLEAR
    A
    ADD
    05
    MEND
    SUBA
    MACRO
    CLEAR
    A
    SUB
    05
    MEND

    name.dat

    ADDA
    SUBA

    out.dat

    COPY
    START
    0
    CLEAR
    X
    CLEAR
    A
    ADD
    05
    CLEAR
    A
    SUB
    05
    END

    Sunday, October 17, 2010

    Symbol Table with Hashing

    Question

    Implementation of Symbol Table with Suitable Hashing.

    Program

    #include "stdio.h"
    #include "stdlib.h"
    #include "string.h"
    struct symtable
    {
    int address;
    char label[10];
    int flag;
    }a[11];
    int hashvalue,addr,i,ch;
    char lbl[10];
    void display()
    {
    printf("\n The Symbol Table is \n");
    printf("\n Hash Values Address Label\n");
    for(i=0;i<11;i++)
    {
    printf("\n\n %d %d %s",i,a[i].address,a[i].label);
    }
    }
    void create()
    {
    char opt[10];
    do
    {
    printf("\n Enter the address:");
    scanf("%d",&addr);
    hashvalue=addr%11;
    printf("\n Enter the Label:");
    scanf("%s",lbl);
    if(a[hashvalue].flag==0)
    {
    a[hashvalue].address=addr;
    strcpy(a[hashvalue].label,lbl);
    a[hashvalue].flag=1;
    }
    else
    {
    int allocated=0;
    for(hashvalue++;hashvalue<11;hashvalue++)
    {
    if(a[hashvalue].flag==0)
    {
    a[hashvalue].address=addr;
    strcpy(a[hashvalue].label,lbl);
    a[hashvalue].flag=1;
    allocated=1;
    break;
    }
    }
    if(allocated==0)
    {
    hashvalue=0;

    for(;hashvalue<11;hashvalue++)
    {
    if(a[hashvalue].flag==0)
    {
    a[hashvalue].address=addr;
    strcpy(a[hashvalue].label,lbl);
    a[hashvalue].flag=1;
    break;
    }
    }
    }
    }
    printf("\n Continue(y/n)? ");
    scanf("%s",opt);
    }while(strcmp(opt,"n")!=0);
    display();
    }

    void search()
    {
    printf("\n Enter the label:");
    scanf("%s",lbl);
    for(i=0;i<11;i++)
    {
    if(a[i].flag==1)
    {
    if(strcmp(a[i].label,lbl)==0)
    {
    printf("\n The label %s found at address %d",lbl,a[i].address);
    }
    }
    }
    }
    void main()
    {
    for(i=0;i<10;i++)
    {
    a[i].flag = 0;
    a[i].address=0;
    strcpy(a[i].label," ");
    }
    while(1)
    {
    ph:
    printf("\n\n 1.Create a Symbol Table \n 2.Search in Symbol Table \n 3.Exit");
    printf("\n\n Enter your choice:");
    scanf("%d",&ch);
    switch(ch)
    {
    case 1:
    create();
    break;
    case 2:
    search();
    break;
    case 3:
    exit(0);
    break;
    default:
    printf("\n Enter a valid option:");
    goto ph;
    }
    }
    }

    Download Source Code

    Thursday, October 14, 2010

    Designing a Two Pass Assembler

    In this post I will explain the basic logic involved in designing a two pass assembler and write the 'C' program code to simulate the Pass1 and Pass2 of the Assembler.

    A Simple Assembler consists of Two data structures namely,

    1. OPTAB(Operation Table)
    2. SYMTAB(Symbol Table)

    Note - LOCCTR is a variable that is used in assigning the addresses. Initially it is assigned to the address specified after 'START' , then after reading each instruction it is incremented to the length of the Instruction so as to keep track of the location.

    OPTAB

    1. In a simple Assembler it looks for menomic operation code and translate the into machine language equivalents.

    2. In a complex Assemblers, it also contains information about instruction format and length.

    3. OPTAB in first pass is used to find the instruction length for incrementing LOCCTR, and in second pass tells which information format to use in assembling the instruction.

    4. Organised as a Hash Table with mnemonic opcode as Key.

    SYMTAB

    1. Includes name and address for each Label in the program.

    2. During Pass1 of the assembler,labels and the address specified by LOCCTR are entered into SYMTAB as we encounter the labels in the program.

    3. During Pass2 we lookup the Symbols used as operands and obtain the address to be inserted in the assembled instructions.

    4. Implemented as a hash table for efficiency. However the hash function must be properly selected.

    Programming the Pass1 and Pass2


    Now let us focus on programming the pass1 in 'C' language.

    Pass1

    • Here we use three files namely - Input.c, Intermediate.c, SymbolTable.c (you can name it as you wish, but use this for clarity).
    • Pass1 usually wrires Intermediate file that contains source statement together with its assigned address.
    • Here we use a function named "wordcount" to compute the number of words in each line of the program.
    Let us begin with the "wordcount() function." It reads the "Input.c" file which contains the Input or source program.

    variables used - "word" to keep track of the number of words, "i" to keep track of the line number, character "c" to fetch each character from the input file.

    Logic

    1. If "c" encounters a blank space increment the word and if it encounters a "\n i.e. new line", increment the word and then display the number of words in the line which is ofcourse the value in "word". For later usage let us store the no.of words in each line in a global array count.

    2. Increment the i value, and set word to 0 and repeat step 1.

    3. Repeat the above steps until EOF(End of File) is encountered.

    Code

    int count[20];
    void wordcount()
    {
    FILE *f3;
    int word=0,i=1;
    char c;

    f3=fopen("INPUT.C","r");
    c=fgetc(f3);
    while(c!=EOF)
    {
    if(c==' ') // blank space
    word+=1;
    if(c=='\n')
    {
    word+=1;
    count[i] = word;
    printf("\n No.of Words in line number %d is %d",i,word);
    i++;
    word=0; // Important
    }
    c=fgetc(f3);
    }
    fclose(f3);
    }

    After wordcount we changer our focus to construct the INTERMEDIATE.C and SYMBOLTABLE.c,

    Logic

    1. Use the LOCCTR to keep track of addresses.
    2. We read each line from INPUT.C,
    • If the line has 1 word, then it means it has only a "Mnemonic" code, so add the mnemonic to INTERMEDIATE.c along with LOCCTR value.
    • If the line has 2 words, then it means it has "Mnemonic" as well as an "operand". Add both of this and LOCCTR value in INTERMEDIATE.c.
    • If the line has 3 words, then it has "Mnemonic", "Operand" as well as label before the mnemonic. So add Label, Mnemonic, operand and LOCCTR address to the Intermediate.c.
    3. Repeat the step 2 until the end of file INPUT.c
    4. Thus all the tables get constructed.

    Code

    FILE *f1,*f2,*f3;

    int linenumber, locctr;
    char lbl[20], mne[10], opd[10], ch;

    printf("\n Word count for Input program");
    wordcount();

    f1=fopen("INPUT.c","r");
    f2=fopen("INTERMEDIATE.c","w");
    f3=fopen("SYMTAB.c","w");

    fscanf(f1,"%s %s %x", lbl, mne, &locctr);
    linenumber=2;
    while(!feof(f1))
    {

    if(count[linenumber]==1)
    {
    fscanf(f1,"%s\n",mne);
    fprintf(f3,"%x \t %s\n",locctr,mne);
    }

    if(count[linenumber]==2)
    {
    fscanf(f1,"%s %s\n",mne,opd);
    fprintf(f3,"%x \t %s \t %s\n",locctr,mne,opd);
    }
    if(count[linenumber]==3)
    {
    fscanf(f1,"%s %s %s\n",lbl,mne,opd);
    fprintf(f3,"%x \t %s \t %s \t %s\n",locctr,lbl,mne,opd);
    fprintf(f2,"%s \t %x",lbl,locctr);
    }

    linenumber+=1;

    if(strcmp(mne,"WORD")==0)
    locctr+=3;
    else if(strcmp(mne,"BYTE")==0)
    locctr+=strlen(opd);
    else if(strcmp(mne,"RESW")==0)
    locctr+=3*atoi(opd);
    else if(strcmp(mne,"RESB")==0)
    locctr+=atoi(opd);

    //atoi converts string to integer

    else
    locctr+=3;
    }
    fclose(f1);
    fclose(f2);
    fclose(f2);
    }


    (Programming Pass2 will be explained soon)

    Until then,

    G.Vivek Venkatesh

    Sunday, October 3, 2010

    Problem with my Internet Connection

    Hi friends, there is some problem with my BSNL Internet Connection for the past three days. Downloads are happening at 1 Kbps . I have written a complaint to BSNL and the problem is yet to be rectified. Thats why could not post any programs.

    Hope the problem is rectified soon.

    Until then
    Vivek Venkatesh G

    Tuesday, September 21, 2010

    Packet Capturing using Raw Socket Program

    Question

    Program using Raw Sockets(like Packet Capturing)

    Note

    You must have root privilege in order to run this program.

    Download Source Code(preferred than viewing it Live on blog)

    program

    output

    Program

    (rawudp.c)

    #include "unistd.h"
    #include "stdio.h"
    #include "sys/socket.h"
    #include "netinet/ip.h"
    #include "netinet/udp.h"

    #define PCKT_LEN 8192

    // The IP header's structure
    struct ipheader {
    unsigned char iph_ihl:5, iph_ver:4;
    unsigned char iph_tos;
    unsigned short int iph_len;
    unsigned short int iph_ident;
    unsigned char iph_flag;
    unsigned short int iph_offset;
    unsigned char iph_ttl;
    unsigned char iph_protocol;
    unsigned short int iph_chksum;
    unsigned int iph_sourceip;
    unsigned int iph_destip;
    };

    // UDP header's structure
    struct udpheader {
    unsigned short int udph_srcport;
    unsigned short int udph_destport;
    unsigned short int udph_len;
    unsigned short int udph_chksum;
    };

    // Function for checksum calculation.
    unsigned short csum(unsigned short *buf, int nwords)
    { //
    unsigned long sum;
    for(sum=0; nwords>0; nwords--)
    sum += *buf++;
    sum = (sum >> 16) + (sum &0xffff);
    sum += (sum >> 16);
    return (unsigned short)(~sum);
    }

    int main(int argc, char *argv[])
    {
    int sd;
    char buffer[PCKT_LEN];
    // Our own headers' structures
    struct ipheader *ip = (struct ipheader *) buffer;
    struct udpheader *udp = (struct udpheader *) (buffer + sizeof(struct ipheader));
    // Source and destination addresses: IP and port
    struct sockaddr_in sin, din;
    int one = 1;
    const int *val = &one;

    memset(buffer, 0, PCKT_LEN);

    // Create a raw socket with UDP protocol
    sd = socket(PF_INET, SOCK_RAW, IPPROTO_UDP);
    if(sd < sin_family =" AF_INET;" sin_family =" AF_INET;" sin_port =" htons(atoi(argv[2]));" sin_port =" htons(atoi(argv[4]));" s_addr =" inet_addr(argv[1]);" s_addr =" inet_addr(argv[3]);">iph_ihl = 5;
    ip->iph_ver = 4;
    ip->iph_tos = 16;
    ip->iph_len = sizeof(struct ipheader) + sizeof(struct udpheader);
    ip->iph_ident = htons(54321);
    ip->iph_ttl = 64; // hops
    ip->iph_protocol = 17; // UDP
    ip->iph_sourceip = inet_addr(argv[1]);//Source IP address
    ip->iph_destip = inet_addr(argv[3]);// destination IP address

    // Fabricate the UDP header.
    udp->udph_srcport = htons(atoi(argv[2]));//source port
    udp->udph_destport = htons(atoi(argv[4]));//destination port
    udp->udph_len = htons(sizeof(struct udpheader));
    // Calculate the checksum
    ip->iph_chksum = csum((unsigned short *)buffer, sizeof(struct ipheader) + sizeof(struct udpheader));

    if(setsockopt(sd, IPPROTO_IP, IP_HDRINCL, val, sizeof(one)) < count =" 1;">iph_len, 0, (struct sockaddr *)&sin, sizeof(sin)) < 0)
    {
    perror("sendto() error");
    exit(-1);
    }
    else
    {
    printf("Count #%u - sendto() is OK.\n", count);
    sleep(2);
    }
    }
    close(sd);
    return 0;
    }

    Sunday, September 19, 2010

    Remote Procedure Call Program in C

    Question

    To implement Remote Procedure Call, and perform addition and subtraction of two numbers.

    (Explanation will be given soon).

    Program

    simp.x

    #define VERSION_NUMBER 1

    %#define foo 127

    struct operands {

    int x;

    int y;

    };


    program SIMP_PROG {

    version SIMP_VERSION {

    int ADD(operands) = 1;

    int SUB(operands) = 2;

    } = VERSION_NUMBER;

    } = 555555555;


    simpclient.c

    /* RPC client for simple addition example */


    #include "stdio.h"

    #include "simp.h" /* Created for us by rpcgen - has everything we need ! */


    /* Wrapper function takes care of calling the RPC procedure */


    int add( CLIENT *clnt, int x, int y) {

    operands ops;

    int *result;


    /* Gather everything into a single data structure to send to the server */

    ops.x = x;

    ops.y = y;


    /* Call the client stub created by rpcgen */

    result = add_1(&ops,clnt);

    if (result==NULL) {

    fprintf(stderr,"Trouble calling remote procedure\n");

    exit(0);

    }

    return(*result);

    }


    /* Wrapper function takes care of calling the RPC procedure */


    int sub( CLIENT *clnt, int x, int y) {

    operands ops;

    int *result;


    /* Gather everything into a single data structure to send to the server */

    ops.x = x;

    ops.y = y;


    /* Call the client stub created by rpcgen */

    result = sub_1(&ops,clnt);

    if (result==NULL) {

    fprintf(stderr,"Trouble calling remote procedure\n");

    exit(0);

    }

    return(*result);

    }



    int main( int argc, char *argv[]) {

    CLIENT *clnt;

    int x,y;

    if (argc!=4) {

    fprintf(stderr,"Usage: %s hostname num1 num\n",argv[0]);

    exit(0);

    }


    /* Create a CLIENT data structure that reference the RPC

    procedure SIMP_PROG, version SIMP_VERSION running on the

    host specified by the 1st command line arg. */


    clnt = clnt_create(argv[1], SIMP_PROG, SIMP_VERSION, "udp");


    /* Make sure the create worked */

    if (clnt == (CLIENT *) NULL) {

    clnt_pcreateerror(argv[1]);

    exit(1);

    }


    /* get the 2 numbers that should be added */

    x = atoi(argv[2]);

    y = atoi(argv[3]);



    printf("%d + %d = %d\n",x,y, add(clnt,x,y));

    printf("%d - %d = %d\n",x,y, sub(clnt,x,y));

    return(0);

    }



    simpservice.c

    /* Definition of the remote add and subtract procedure used by

    simple RPC example

    rpcgen will create a template for you that contains much of the code

    needed in this file is you give it the "-Ss" command line arg.

    */


    #include "simp.h"


    /* Here is the actual remote procedure */

    /* The return value of this procedure must be a pointer to int! */

    /* we declare the variable result as static so we can return a

    pointer to it */


    int *

    add_1_svc(operands *argp, struct svc_req *rqstp)

    {

    static int result;

    printf("Got request: adding %d, %d\n", argp->x, argp->y);

    result = argp->x + argp->y;

    return (&result);

    }


    int *

    sub_1_svc(operands *argp, struct svc_req *rqstp)

    {

    static int result;

    printf("Got request: subtracting %d, %d\n", argp->x, argp->y);

    result = argp->x - argp->y;

    return (&result);

    }


    Compilation and Output


    Server


    vivek@ubuntu~$ rpcgen -C -a simp.x

    vivek@ubuntu~$ cc -o server simpservice.c simp_svc.c simp_xdr.c

    vivek@ubuntu~$ ./server

    Got request: adding 4, 5

    Got request: subtracting 4, 5


    Client


    vivek@ubuntu~$ cc -o client simpclient.c simp_clnt.c simp_xdr.c

    vivek@ubuntu~$ ./client linux 4 5

    4 + 5 = 9

    4 - 5 = -1


    Download Source Code





    Thursday, September 16, 2010

    OPAC System program in Java

    Question

    Develop a simple OPAC system for library using even-driven and concurrent programming paradigms of Java. Use JDBC to connect to a back-end database.

    Procedure

    1. Create a new Database file in MS ACCESS (our backend) named “books.mdb”.

    2. Then create a table named “Library” in it.

    3. The table Library contains the following fields and data types,

    1. AuthorName – Text

    2. ISBN – Text

    3. BookName - Text

    4. Price - Number

    5. Publisher – Text

    1. Enter various records as you wish.

    2. Save the database file.

    3. Next step is to add our “books.mdb” to the System DSN. To do that follow the procedure given below,

    1. Go to Start-> Control Panel -> Administrative tools.

    2. In that double click “Data Sources (ODBC)”.

    3. ODBC Data Source Administrator dialog appears.

    4. In that select “System DSN” tab and click the Add Button.

    5. Select “Microsoft Access Driver(*.mdb)” and click Finish.

    6. ODBC Microsoft Access Setup appears. In the “Data Source name” type “Library”.

    7. Click on the “Select” button and choose your database file. Then click ok.

    Now your database file gets added to the System DSN. It should look like below,


    Now execute the following code “Library.java”.


    Library.java

    import java.sql.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;

    public class Library implements ActionListener
    {
    JRadioButton rbauthor = new JRadioButton("Search by Author name");
    JRadioButton rbbook = new JRadioButton("Search by Book name");
    JTextField textfld = new JTextField(30);
    JLabel label = new JLabel("Enter Search Key");
    JButton searchbutton = new JButton("Search");
    JFrame frame = new JFrame();
    JTable table;
    DefaultTableModel model;
    String query = "select * from Library";

    public Library()
    {
    frame.setTitle("Online Public Access Catalog");
    frame.setSize(500,600);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new BorderLayout());

    JPanel p1 = new JPanel();
    JPanel p2 = new JPanel();
    JPanel p3 = new JPanel();

    p1.setLayout(new FlowLayout());
    p1.add(label);
    p1.add(textfld);

    ButtonGroup bg = new ButtonGroup();
    bg.add(rbauthor);
    bg.add(rbbook);

    p2.setLayout(new FlowLayout());
    p2.add(rbauthor);
    p2.add(rbbook);
    p2.add(searchbutton);
    searchbutton.addActionListener(this);

    p3.setLayout(new BorderLayout());
    p3.add(p1,BorderLayout.NORTH);
    p3.add(p2,BorderLayout.CENTER);

    frame.add(p3,BorderLayout.NORTH);
    addTable(query);
    frame.setVisible(true);
    }
    public void addTable(String s)
    {
    try
    {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection conn = DriverManager.getConnection("jdbc:odbc:Library","","");
    Statement st = conn.createStatement();

    ResultSet rs = st.executeQuery(s);
    ResultSetMetaData md = rs.getMetaData();
    int cols = md.getColumnCount();
    model = new DefaultTableModel(1,cols);
    table = new JTable(model);
    String[] tabledata = new String[cols];
    int i=0;
    while(i0)
    model.removeRow(0);
    frame.remove(table);
    addTable(query);
    }
    public static void main(String[] args)
    {
    new Library();
    }

    }

    Screenshots of Output

    (Opening Screen)


    (author Search)

    (Book Search)



    Download the Source Code


    Library.java



    Saturday, September 11, 2010

    Multithreading using Pipes Program

    Question

    Write a multi-threaded Java program to print all numbers below 100,000 that are
    both prime and fibonacci number (some examples are 2, 3, 5, 13, etc.). Design a
    thread that generates prime numbers below 100,000 and writes them into a pipe.
    Design another thread that generates fibonacci numbers and writes them to another pipe. The main thread should read both the pipes to identify numbers common to both.

    Program Written by
    Mr.G.Kumaresan sir.

    Program


    import java.util.*;
    import java.io.*;

    class Fibonacci extends Thread
    {
    private PipedWriter out = new PipedWriter();
    public PipedWriter getPipedWriter()
    {
    return out;
    }
    public void run()
    {
    Thread t = Thread.currentThread();
    t.setName("Fibonacci");
    System.out.println(t.getName() + " thread started");
    int fibo1=0,fibo2=1,fibo=0;
    while(true)
    {
    try
    {
    fibo = fibo1 + fibo2;
    if(fibo>100000)
    {
    out.close();
    break;
    }
    out.write(fibo);
    sleep(1000);
    }
    catch(Exception e)
    {
    System.out.println("Fibonacci:"+e);
    }
    fibo1=fibo2;
    fibo2=fibo;
    }
    System.out.println(t.getName() + " thread exiting");

    }
    }
    class Prime extends Thread
    {
    private PipedWriter out1 = new PipedWriter();
    public PipedWriter getPipedWriter()
    {
    return out1;
    }
    public void run()
    {
    Thread t= Thread.currentThread();
    t.setName("Prime");
    System.out.println(t.getName() + " thread Started...");
    int prime=1;
    while(true)
    {
    try
    {
    if(prime>100000)
    {
    out1.close();
    break;
    }
    if(isPrime(prime))
    out1.write(prime);
    prime++;
    sleep(0);
    }
    catch(Exception e)
    {
    System.out.println(t.getName() + " thread exiting.");
    System.exit(0);
    }
    }
    }
    public boolean isPrime(int n)
    {
    int m=(int)Math.round(Math.sqrt(n));
    if(n==1 || n==2)
    return true;
    for(int i=2;i<=m;i++)
    if(n%i==0)
    return false;
    return true;
    }
    }
    public class PipedIo
    {
    public static void main(String[] args) throws Exception
    {
    Thread t=Thread.currentThread();
    t.setName("Main");
    System.out.println(t.getName() + " thread Started...");
    Fibonacci fibonacci = new Fibonacci();
    Prime prime = new Prime();
    PipedReader fpr = new PipedReader(fibonacci.getPipedWriter());
    PipedReader ppr = new PipedReader(prime.getPipedWriter());
    fibonacci.start();
    prime.start();
    int fib=fpr.read(), prm=ppr.read();
    System.out.println("The numbers common to PRIME and FIBONACCI:");
    while((fib!=-1) && (prm!=-1))
    {
    while(prm<=fib)
    {
    if(fib==prm)
    System.out.println(prm);
    prm=ppr.read();
    }
    fib=fpr.read();
    }
    System.out.println(t.getName() + " thread exiting");
    }
    }

    Download Source Code

    PipedIo.java

    Tuesday, September 7, 2010

    Electives for 6th Semester

    We have two Electives for sixth sem,

    of which I feel these to be better

    Elective 1

    We can take either CS2023(Advanced Java Programming) or IT2353(Web Technology)....Both are of use to us.

    Elective 2

    Ofc, Numerical Methods would be an unanimous choice....

    What do you feel????? What's your choice??

    Monday, September 6, 2010

    Software Engineering Important Ques

    Unit 2 Important Ques in S/W Engineering.

    Part A

    1.List out the elements of Analysis Modelling. (with diagram).
    2.Define Cardinality and Modality. (with diagram)
    3. Compare and Contrast throw away and evolutionary prototyping.
    4. Compare STD and DFD (with diagram).
    5. Write the distinct steps in Requirement Engineering process.
    6. Why requirement Elicitation process is difficult?
    7. What are steps required to build ERD?
    8. Benefits of Prototyping.
    9. What is SRS, and its Characteristics.

    Part B

    1. Explain in detail about Requirement Engineering process.
    2. Explain in detail about Data, Functional and Behavioral modelling along with diagrams.

    Friday, August 27, 2010

    A Simple Scientific Calculator in Java

    Hi Friends....just had some free time, so thought of creating a "Simple Calculator" in Java...As claims it is "Simple" and don't expect anything Big out of it (Just some basic operations).....I have added the source code for it too....

    (You can use it to Create your own Calculator and may be which is more efficient than mine..Just in case u find any flaws in this, pls do mail me abt it..)

    Screenshot of "Calculator" that I created in Java




    Download the Source Code and the Application


    Comments Welcomed...

    G.Vivek Venkatesh

    Thursday, August 26, 2010

    One Bit Sliding Window Protocol

    Question - To write a C program to Implement One Bit Sliding Window Protocol.

    Screenshot of Output



    Program


    sender.c (server)

    #include "stdio.h"
    #include "sys/types.h"
    #include "netinet/in.h"
    #include "string.h"
    #include "sys/socket.h"
    #include "stdlib.h"
    #include "unistd.h"
    main()
    {
    int sd,i,r,bi,nsd,port,frame,prev_frame=0,count=0;;
    char ack[5],buff[30];
    struct sockaddr_in ser,cli;
    if((sd=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))==-1)
    {
    printf("\n Socket problem");
    return 0;
    }
    printf("\n Socket created\n");
    bzero((char*)&cli,sizeof(ser));
    printf("ENTER PORT NO:\n");
    scanf("%d",&port);
    printf("\n Port Address is %d\n:",port);
    ser.sin_family=AF_INET;
    ser.sin_port=htons(port);
    ser.sin_addr.s_addr=htonl(INADDR_ANY);

    bi=bind(sd,(struct sockaddr *)&ser,sizeof(ser));
    if(bi==-1)
    {
    printf("\n bind error, port busy, plz change port in client and server");
    return 0;
    }
    i=sizeof(cli);
    listen(sd,5);
    nsd = accept(sd,((struct sockaddr *)&cli),&i);
    if(nsd==-1)
    {
    printf("\ncheck the description parameter\n");
    return 0;
    }
    printf("\nConnection accepted.");
    while(count<5)
    {

    ph:
    printf("\nSending FRAME %d to the Receiver...\n",prev_frame);
    snprintf(buff,sizeof(buff),"%d",prev_frame);
    send(nsd,buff,30,0);

    r = recv(nsd,ack,5,0);
    if(strcmp(ack,"ack")==0 || strcmp(ack,"ACK")==0)

    { count++;
    if(prev_frame==0) prev_frame=1;
    else prev_frame = 0;
    }
    else if(strcmp(ack,"nak")==0 || strcmp(ack,"NAK")==0)
    {
    printf("\n NAK: So again sending the Previous frame...\n"); goto ph;
    }
    }
    printf("\n Bye..");
    send(nsd,"EOF",4,0);
    close(sd);
    close(nsd);
    return 0;
    }


    receiver.c (client)

    #include "stdio.h"
    #include "sys/types.h"
    #include "netinet/in.h"
    #include "string.h"
    #include "sys/socket.h"
    #include "stdlib.h"
    #include "unistd.h"
    int main()
    {
    int sd,con,port,i;
    char content[30],ack[3];
    struct sockaddr_in cli;
    if((sd=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))==-1)
    {
    printf("\n Socket problem");
    return 0;
    }
    bzero((char*)&cli,sizeof(cli));
    cli.sin_family = AF_INET;
    printf("ENTER PORT NO");
    scanf("%d",&port);
    cli.sin_port=htons(port);
    cli.sin_addr.s_addr=htonl(INADDR_ANY);
    con=connect(sd,(struct sockaddr*)&cli,sizeof(cli));
    if(con==-1)
    {
    printf("\n connection error");
    return 0;
    }
    i=recv(sd,content,30,0);
    while(strcmp(content,"EOF") != 0)
    {
    printf("Received from Sender: Frame %s \n",content);
    ph:

    printf("\n Acknowledgement(ACK/NAK) : ");
    scanf("%s",ack);
    if(!(strcmp(ack,"ack")==0 || strcmp(ack,"nak")==0 || strcmp(ack,"ACK")==0 || strcmp(ack,"NAK")==0))
    {
    printf("\n Not a valid Acknowledgement..use ACK or NAK..\n ");
    goto ph;

    }
    send(sd,ack,5,0);
    i=recv(sd,content,30,0);
    }
    printf("\n\n Bye...");
    close(sd);
    return 0;
    }

    Download Source Codes

    sender.c

    receiver.c


    Program Written by G.Vivek Venkatesh




    Tuesday, August 24, 2010

    Object Serialization Program in Java

    Question

    Design classes for Currency, Rupee, and Dollar. Write a program that randomly generates Rupee and Dollar objects and write them into a file using object serialization. Write another program to read that file, convert to Rupee if it reads a Dollar, while leave the value as it is if it reads a Rupee.

    Program

    (credits to Kumresan Sir)


    SerializationWrite.java

    import java.io.*;
    import java.util.*;

    class Currency implements Serializable
    {
    protected String currency;
    protected int amount;

    public Currency(String cur, int amt)
    {
    this.currency = cur;
    this.amount = amt;
    }
    public String toString()
    {
    return currency + amount;
    }
    public String dollarToRupee(int amt)
    {
    return "Rs" + amt * 45;
    }
    }
    class Rupee extends Currency
    {
    public Rupee(int amt)
    {
    super("Rs",amt);
    }
    }
    class Dollar extends Currency
    {
    public Dollar(int amt)
    {
    super("$",amt);
    }
    }
    public class SerializationWrite
    {
    public static void main(String args[])
    {
    Random r = new Random();
    try
    {
    Currency currency;
    FileOutputStream fos = new FileOutputStream("serial.txt");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    System.out.println("Writing to file using Object Serialization:");
    for(int i=1;i<=25;i++)
    {
    Object[] obj = { new Rupee(r.nextInt(5000)),new Dollar(r.nextInt(5000)) };
    currency = (Currency)obj[r.nextInt(2)]; // RANDOM Objects for Rs and $
    System.out.println(currency);
    oos.writeObject(currency);
    oos.flush();
    }
    oos.close();
    }
    catch(Exception e)
    {
    System.out.println("Exception during Serialization: " + e);
    }
    }
    }

    SerializationRead.java

    import java.io.*;
    import java.util.*;

    public class SerializationRead
    {
    public static void main(String args[])
    {
    try
    {
    Currency obj;
    FileInputStream fis = new FileInputStream("serial.txt");
    ObjectInputStream ois = new ObjectInputStream(fis);
    System.out.println("Reading from file using Object Serialization:");
    for(int i=1;i<=25;i++)
    {
    obj = (Currency)ois.readObject();
    if((obj.currency).equals("$"))
    System.out.println(obj + " = " + obj.dollarToRupee(obj.amount));
    else
    System.out.println(obj + " = " + obj);

    }
    ois.close();
    }
    catch(Exception e)
    {
    System.out.println("Exception during deserialization." + e);
    }
    }
    }


    Output

    vivek@ubuntu:~/Desktop$ javac SerializationWrite.java
    vivek@ubuntu:~/Desktop$ java SerializationWrite

    Writing to file using Object Serialization:
    $4645
    Rs105
    $2497
    $892
    Rs1053
    Rs1270
    $1991
    Rs4923
    Rs4443
    Rs3537
    Rs2914
    $53
    $561
    $4692
    Rs860
    $2764
    Rs752
    $1629
    $2880
    Rs2358
    Rs3561
    $3796
    Rs341
    Rs2010
    Rs427

    vivek@ubuntu:~/Desktop$ javac SerializationRead.java
    vivek@ubuntu:~/Desktop$ java SerializationRead

    Reading from file using Object Serialization:
    $4645 = Rs209025
    Rs105 = Rs105
    $2497 = Rs112365
    $892 = Rs40140
    Rs1053 = Rs1053
    Rs1270 = Rs1270
    $1991 = Rs89595
    Rs4923 = Rs4923
    Rs4443 = Rs4443
    Rs3537 = Rs3537
    Rs2914 = Rs2914
    $53 = Rs2385
    $561 = Rs25245
    $4692 = Rs211140
    Rs860 = Rs860
    $2764 = Rs124380
    Rs752 = Rs752
    $1629 = Rs73305
    $2880 = Rs129600
    Rs2358 = Rs2358
    Rs3561 = Rs3561
    $3796 = Rs170820
    Rs341 = Rs341
    Rs2010 = Rs2010
    Rs427 = Rs427


    Download Source Codes

    SerializationWrite.java

    SerializationRead.java

    Thursday, August 19, 2010

    DNS Server Client Program


    (Screenshot of output)


    dnsserver.c


    #include "stdio.h"
    #include "string.h"
    #include "stdlib.h"
    #include "unistd.h"
    #include "errno.h"
    #include "sys/socket.h"
    #include "sys/types.h"
    #include "netinet/in.h"
    #include "arpa/inet.h"
    #define MAXBUFFLEN 500
    int main(int argc,char *argv[])
    {
    int sockfd,port,bi;
    char buff[MAXBUFFLEN-1];
    struct sockaddr_in servaddr,cliaddr;
    int addr_len,numbytes;
    sockfd=socket(AF_INET,SOCK_DGRAM,0);
    if(sockfd==-1)
    {
    perror("Socket()");
    return 0;
    }
    printf("\n Enter the port no:");
    scanf("%d",&port);
    printf("\n The Port no is:%d",port);
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(port);
    servaddr.sin_addr.s_addr = INADDR_ANY;
    memset(servaddr.sin_zero,'\0',8);
    bi=bind(sockfd,(struct sockaddr*)&servaddr,sizeof(struct sockaddr));
    if(bi==-1)
    {
    perror("bind");
    return 0;
    }
    addr_len = sizeof(struct sockaddr*);
    numbytes = recvfrom(sockfd,buff,MAXBUFFLEN-1,0,(struct sockaddr*)&cliaddr,&addr_len);
    printf("\n Server Got-Packet from %s",inet_ntoa(cliaddr.sin_addr));
    printf("\n Server packet is %d bytes long.",numbytes);
    buff[numbytes]='\0';
    printf("\n The Server packet contains %s",buff);
    close(sockfd);
    return 0;
    }

    dnsclient.c

    #include "stdio.h"
    #include "string.h"
    #include "stdlib.h"
    #include "unistd.h"
    #include "errno.h"
    #include "sys/socket.h"
    #include "sys/types.h"
    #include "netinet/in.h"
    #include "arpa/inet.h"
    #include "netdb.h"
    int main(int argc,char *argv[])
    {
    int sockfd,port;
    struct sockaddr_in servaddr;
    struct hostent *he;
    int addr_len,numbytes;
    if(argc!=3)
    {
    fprintf(stderr,"Client Usage : %s \n",argv[0]);
    exit(1);
    }
    if((he=gethostbyname(argv[1]))==NULL)
    {
    perror("gethostbyname error");
    exit(1);
    }
    sockfd=socket(AF_INET,SOCK_DGRAM,0);
    if(sockfd==-1)
    {
    perror("Socket.");
    return 0;
    }
    printf("\n Enter the port no:");
    scanf("%d",&port);
    printf("\n The port no is : %d",port);
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(port);
    servaddr.sin_addr = *((struct in_addr*)he->h_addr);
    memset(&(servaddr.sin_zero),'\0',8);
    numbytes = sendto(sockfd,argv[2],sizeof(argv[2]),0,(struct sockaddr*)&servaddr,sizeof(struct sockaddr));
    printf("\n Sent %d bytes to %s",numbytes,inet_ntoa(servaddr.sin_addr));
    close(sockfd);
    return 0;
    }

    Download Source Code

    dnsserver.c

    dnsclient.c


    UDP Time Server Program

    tserver.c

    #include "stdio.h"
    #include "string.h"
    #include "stdlib.h"
    #include "sys/socket.h"
    #include "sys/types.h"
    #include "netinet/in.h"
    #include "time.h>
    int main()
    {
    int sfd,r,bi,port;
    char buff[1024];
    struct sockaddr_in servaddr,cliaddr;
    socklen_t clilen;
    sfd=socket(AF_INET,SOCK_DGRAM,0);
    if(sfd==-1)
    {
    perror("Socket");
    return 0;
    }
    memset(servaddr.sin_zero,'\0',sizeof(servaddr.sin_zero));
    printf("\n Enter the port no:");
    scanf("%d",&port);
    printf("\n The port no is:%d",port);
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(port);
    servaddr.sin_addr.s_addr = INADDR_ANY;
    bi=bind(sfd,(struct sockaddr*)&servaddr,sizeof(servaddr));
    if(bi==-1)
    {
    perror("Bind()");
    return 0;
    }
    clilen = sizeof(cliaddr);
    r=recvfrom(sfd,buff,sizeof(buff),0,(struct sockaddr*)&cliaddr,&clilen);
    buff[r]=0;
    time_t ticks;
    ticks = time(NULL);
    snprintf(buff,sizeof(buff),"%24s\r\n",ctime(&ticks));
    sendto(sfd,buff,sizeof(buff),0,(struct sockaddr*)&cliaddr,sizeof(cliaddr));
    exit(0);
    return 0;
    }

    tclient.c

    #include "stdio.h"
    #include "string.h"
    #include "stdlib.h"
    #include "sys/socket.h"
    #include "sys/types.h"
    #include "netinet/in.h"
    int main()
    {
    int listenfd,port,r;
    char buff[1024];
    struct sockaddr_in servaddr,cliaddr;
    socklen_t servlen;
    listenfd = socket(AF_INET,SOCK_DGRAM,0);
    if(listenfd==-1)
    {
    perror("Socket");
    return 0;
    }
    memset(servaddr.sin_zero,'\0',sizeof(servaddr.sin_zero));
    printf("\n Enter the port no:");
    scanf("%d",&port);
    printf("\n The port no is:%d",port);
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(port);
    servaddr.sin_addr.s_addr = INADDR_ANY;
    sendto(listenfd,buff,sizeof(buff),0,(struct sockaddr*)&servaddr,sizeof(servaddr));
    r=recvfrom(listenfd,buff,sizeof(buff),0,(struct sockaddr*)&servaddr,&servlen);
    buff[r]=0;
    printf("\n The time received from the server:%s",buff);
    exit(0);
    return 0;
    }

    Download Source Code


    tserver.c

    tclient.c