Thursday, September 13, 2012

Tuesday, August 7, 2012

Images of Mt Everest

Here are some cool pics of Mt Everest:



Saturday, July 28, 2012

Simple Parsing Scripts

-------------------------------------------------------------------
1) Simple perl script to extract ip address from ipconfig command:


#!/usr/bin/perl

use File::Find;
use File::Copy;
use File::Path;

system ("ipconfig > test.txt");

$filename = "test.txt";
$strToFind = "IPv4";

open(INFILE, $filename) || die "Cannot open file";

$matchFound = 0;

while ($line = )
{
   if ($line =~ /$strToFind/)
    {
      print "$line";
      $matchFound = 1;
    }
}

close(INFILE);

print "\n";

if ($matchFound eq 1)
{
    print "$strToFind was found: $matchFound \n";
}
else
{
    print "$strToFind not found in $filename \n";
}


-----> Simple Ruby Script to parse IP address from ipconfig command <------------


--------------------------------------------------------------------------------------
2) Simple VB Script to parse MAC address and ip address from ipconfig command:

' VBScript Source File 
'
' NAME: myIPfunc.vbs
'
' AUTHOR: Swati Kher
'
' COMMENT: How to parse IPConfig command with vbscript 
'======================================================

Option Explicit


wscript.echo "Mac Address = ["& GetMac() & "]"

wscript.quit(0)

' ********************************************************************************************
' ******** GetMac ********
' ********************************************************************************************

Function GetMac()

   Dim WshShell, oExec , physaddr, macaddr, ipaddr
   Dim iLocation, name, strInputFile, iLoc2, name2

   Dim FSO, objFile
   Dim strLine

   Set WshShell = CreateObject("WScript.Shell") 

   set oExec = WshShell.Exec("cmd.exe /c ipconfig /all")

   physaddr = oExec.StdOut.ReadAll()
   name    = "Physical Address"
   name2   = "IPv4 Address"
   macaddr = "tbd"
  

   iLocation = InStr (physaddr, name)
   iLoc2 = InStr(physaddr, name2)
   
   
   WScript.Echo iLocation
   
   if (iLocation) then

       macaddr = Right(physaddr, Len(physaddr)  - iLocation)
       ipaddr = Right(physaddr, Len(physaddr) - iLoc2)
       
       'WScript.Echo "First Pass: " & macaddr
       iLocation = InStr (1, macaddr, ":")
       iLoc2 = InStr(1, ipaddr, ":")
       
       macaddr = Right(macaddr, Len(macaddr) - iLocation)
       ipaddr = Right(ipaddr, Len(ipaddr) - iLoc2)
       
       Trim(macaddr)
       Trim(ipaddr)
       
       'WScript.Echo "Second : " & macaddr
       'macaddr = Right(macaddr, Len(macaddr) - 17)
       iLocation = InStr (1, macaddr, vbNewLine)
       iLoc2 = InStr(1, ipaddr, vbNewLine)
       
       macaddr = Left(macaddr, iLocation)
       ipaddr = Left(ipaddr, iLoc2)
       
       macaddr = replace(macaddr, "-", "")
       GetMac = macaddr
       'WScript.Echo "Mac address " & macaddr
       WScript.Echo "IP ADDR: " & ipaddr

   end If

   GetMac = macaddr
   set WshShell = Nothing
   Set oExec = Nothing
End Function

------------------------------------------------------
3)  C++ functions to check palindromes and matching strings:


bool isItPali(char *a)
{
int length, mid, j;
    bool match = true;


if (a==NULL)
{
cout<<"Got a NULL String!!"<
return false;
}

length = strlen(a)-1;
mid = length/2;
j = 0;

if (strlen(a)==1)
{
cout<<"Only 1 char!!"<
return true;
}

if (length<=0)
{
cout<<"String was blank!!"<
return false;
}


    while(j<= mid)
{
if (*(a+j) != *(a+length-j))
match = false;
j++;
}


  return match;
}


bool ExpressionMatch(char *a, char *b)
{
int lenA, lenB, i, j, indWld;
bool match = false, done = false;

lenA = strlen(a);
lenB = strlen(b);

i = j = indWld = 0;

    if ((lenA == 0) || (lenB == 0))
return false;


while (!done)
{
if (*(b + j) == '*')
{
j++;
indWld = j;
}
else if (*(b + j) == *(a+i))
{
match = true;
j++;
i++;
}
else if(*(b+j) != *(a+i))
{
i++;
match = false;
if (indWld == 0)
i = lenA;
else if (i< lenA)
j= indWld;
}
if (indWld == lenB)
{
done = true;
if (indWld == 1)
match = true;
}
if (i == lenA)
done = true;
}

return match;
}
-----------------------------------------------------------
4) Java code to compute string LCM

import java.util.*;
import java.util.regex.*;

public class LCMstr {

/**
* @param args
*/
public static String lcm(String a, String b) {
int c = a.length();
int d = b.length();
if (a.charAt(c-1)==b.charAt(0)) {
return(a.concat(b.substring(1))); 
}
if (c >= d) {
    if (a.contains(b)) return a;
}
if (d > c) {
if (b.contains(a)) return b;
}
return a.concat(b);
//System.out.println(a.charAt(0));
//System.out.println("len" + c + a.charAt(c-1));
   //return "err";
}
public static void main(String[] args) {

LCMstr l = new LCMstr();
        System.out.println( l.lcm("ab", "bacd"));
        System.out.println( l.lcm("abcc", "cd"));
        System.out.println( l.lcm("ab", "bad"));
        System.out.println( l.lcm("aba", "abacd"));
        System.out.println(l.lcm("x1", "1x"));
        System.out.println(l.lcm("swati", "1swati"));
        System.out.println(l.lcm("swati1", "swati"));
        System.out.println(l.lcm("x1", "x2"));
        System.out.println(l.lcm("ab", "ab"));
}

}
--------------------------------------------------------
5) java code to compute LCM of two numbers:

public class myLCM {
private void calculateLCM(int x, int y) {

        int lcm = x*y/getGCD(x, y);

        System.out.println(lcm);

 }


private int getGCD(int x, int y) {

       // Make sure, n1 is the bigger number

       int n1 = x > y ? x : y;

       int n2 = x > y ? y : x;

       while(n1%n2 != 0) {

              int remainder = n1%n2;

              n1 = n2;

              n2 = remainder;
       }

       return n2;

}


    public static void main(String[] argv) {

        myLCM x = new myLCM();
        
        x.calculateLCM(2, 3);
        x.calculateLCM(8, 16);
        x.calculateLCM(3,15);
        //x.calculateLCM(10,0);
        x.calculateLCM(11,12);
        x.calculateLCM(15, 20);
        x.calculateLCM(17, 51);

 }
}
---------------------------------------------




Friday, July 27, 2012

Example of Simple HTTPClient in Java


/* compile the following in eclipse : run as java application with the simpleHTTPServer listening on port 5000 (from previous example) */

/* to compile the following external jars are required: commons-codec-1.5.jar, commons-httpclient-3.0.1.jar
              commons-logging-1.1.1.jar, commons-logging-1.1.1-adapters.jar, commons-logging-1.1.1-api.jar
             commons-logging-1.1.1-tests.jar, jackson-core-asl-1.9.2.jar, json-20080701.jar, log4j-1.2.15.jar
              and log4j-1.2.16-sources.jar */

import org.apache.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import org.w3c.dom.*;
import org.json.*;
import org.xml.sax.*;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.xml.transform.stream.StreamResult;
import javax.xml.ws.http.HTTPException;
import org.apache.log4j.*;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
import org.apache.commons.httpclient.methods.PostMethod;

public class myClient {

public myClient() {
System.out.println("myclient");
Logger log = Logger.getLogger("wbs");
}

public Document getTemplateDocument(String fName) {
Document doc = null;
try {
DocumentBuilderFactory docFac = DocumentBuilderFactory.newInstance();

DocumentBuilder docBld = docFac.newDocumentBuilder();

if (!fName.equals(null)) {
File file = new File(fName);
doc = docBld.parse(file);
}
else {
System.out.println("null file");
}
}catch (ParserConfigurationException pce){
pce.printStackTrace();
}catch (IOException ioe) {
ioe.printStackTrace();
}catch (SAXException sxe) {
sxe.printStackTrace();
}
return doc;
}

public String convertDocToString(Document doc){
String xmls = null;

try {
Transformer trans = TransformerFactory.newInstance().newTransformer();
trans.setOutputProperty(OutputKeys.INDENT, "yes");
StreamResult res = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
trans.transform(source, res);
xmls = res.getWriter().toString();
}catch(TransformerConfigurationException tce){
tce.printStackTrace();
}catch(TransformerException te) {
te.printStackTrace();
}
return xmls;
}

public static String execReq(String xmls, String url) {
HttpClientParams cparam = new HttpClientParams();
DefaultHttpMethodRetryHandler retry_H = new DefaultHttpMethodRetryHandler();
cparam.setParameter(HttpClientParams.RETRY_HANDLER, retry_H);
cparam.setParameter(HttpClientParams.HEAD_BODY_CHECK_TIMEOUT, 600000);
cparam.setSoTimeout(600000);
cparam.setConnectionManagerTimeout(600000);
String strXMLFile = xmls;
File input = new File(xmls);
System.out.println("File length: " + input.length());
PostMethod post = null;
try {
post = new PostMethod(url);
HttpClient hc = new HttpClient();
hc.setConnectionTimeout(600000);
post.setRequestBody(new FileInputStream(input));
if (input.lastModified() < Integer.MAX_VALUE){
post.setRequestContentLength((int)input.length());
}
else {
post.setRequestContentLength(EntityEnclosingMethod.CONTENT_LENGTH_CHUNKED);
int stc = hc.executeMethod(post);
System.out.println(post.getResponseBodyAsString());
post.releaseConnection();
System.out.println("statusline: " + post.getStatusLine());
try {
Thread.sleep(100);
}catch(InterruptedException ie) {
System.out.println(ie.getMessage());
}
if(stc == HttpStatus.SC_OK) {
xmls = post.getResponseBodyAsString();
}else {
System.out.println(post.getStatusCode());
}
}
}catch(FileNotFoundException ffe) {
ffe.printStackTrace();
}catch(HTTPException he) {
he.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}finally {
post.releaseConnection();
}
return xmls;
}



public void sendtest() {
Document doc = getTemplateDocument("\\test.xml");
//String request = convertDocToString(doc);
//String response = execReq(request, "http://localhost:5000");

}




public static void main(String[] args) {
// TODO Auto-generated method stub

myClient mc = new myClient();
Document d = mc.getTemplateDocument("\\test.xml");
String request = mc.convertDocToString(d);
System.out.println(request);

        //File inp = new File(request);
     

PostMethod pos = null;
pos = new PostMethod("http://localhost:5000");
HttpClient hc = new HttpClient();
hc.setConnectionTimeout(600000);

try{
//pos.setRequestBody(new FileInputStream(inp));
   //pos.setRequestContentLength((int)inp.length());
 
int stc = hc.executeMethod(pos);
System.out.println(pos.getResponseBodyAsString());
pos.releaseConnection();
System.out.println("statusline: " + pos.getStatusLine());
}catch(HTTPException he) {
he.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}finally {
pos.releaseConnection();
}
}

}

/* sample test message test.xml file  :

*/

Example of A Simple HTTP Server In Java


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

/* This code opens a PFINET TCP socket and listens over port 5000 - to communicate - see following
    client code or simply open a browser and go to http://localhost:5000  which should return HTTP OK code = 200 -> try to figure out how to generate the various error codes below for fun!! */

/* compile this code as follows:  javac myHTTPServer.java
                            then to run it:  java myHTTPServer
                                    To test:  open browser and go to http://localhost:5000  */

public class myHTTPServer extends Thread implements Runnable{


static final String HTML_START =
"" +
"HTTP Server in java" +
"";

static final String HTML_END =
"" +
   "";

  /** http://www.w3.org/Protocols/rfc2616/rfc2616.html **/
  /** 2XX: generally "OK" */
  public static final int HTTP_OK = 200;
  public static final int HTTP_CREATED = 201;
  public static final int HTTP_ACCEPTED = 202;
  public static final int HTTP_NOT_AUTHORITATIVE = 203;
  public static final int HTTP_NO_CONTENT = 204;
  public static final int HTTP_RESET = 205;
  public static final int HTTP_PARTIAL = 206;

  /** 3XX: relocation/redirect */
  public static final int HTTP_MULT_CHOICE = 300;
  public static final int HTTP_MOVED_PERM = 301;
  public static final int HTTP_MOVED_TEMP = 302;
  public static final int HTTP_SEE_OTHER = 303;
  public static final int HTTP_NOT_MODIFIED = 304;
  public static final int HTTP_USE_PROXY = 305;

 /** 4XX: client error */
  public static final int HTTP_BAD_REQUEST = 400;
  public static final int HTTP_UNAUTHORIZED = 401;
  public static final int HTTP_PAYMENT_REQUIRED = 402;
  public static final int HTTP_FORBIDDEN = 403;
  public static final int HTTP_NOT_FOUND = 404;
  public static final int HTTP_BAD_METHOD = 405;
  public static final int HTTP_NOT_ACCEPTABLE = 406;
  public static final int HTTP_PROXY_AUTH = 407;
  public static final int HTTP_CLIENT_TIMEOUT = 408;
  public static final int HTTP_CONFLICT = 409;
  public static final int HTTP_GONE = 410;
  public static final int HTTP_LENGTH_REQUIRED = 411;
  public static final int HTTP_PRECON_FAILED = 412;
  public static final int HTTP_ENTITY_TOO_LARGE = 413;
  public static final int HTTP_REQ_TOO_LONG = 414;
  public static final int HTTP_UNSUPPORTED_TYPE = 415;

  /** 5XX: server error */
  public static final int HTTP_SERVER_ERROR = 500;
  public static final int HTTP_INTERNAL_ERROR = 501;
  public static final int HTTP_BAD_GATEWAY = 502;
  public static final int HTTP_UNAVAILABLE = 503;
  public static final int HTTP_GATEWAY_TIMEOUT = 504;
  public static final int HTTP_VERSION = 505;


int count = 0;

/* create server socket here */

     Socket conn = null;
     BufferedReader inFromClient = null;
     DataOutputStream outToClient = null;

     public myHTTPServer (Socket client)
     {
         conn = client;
         count = 0;
     }

     public void sendFile(FileInputStream fin, DataOutputStream out) throws Exception {
    byte[] buffer = new byte[1024];
    int bytesRead;

    while ((bytesRead = fin.read(buffer)) != -1)
    {
out.write(buffer, 0, bytesRead);
}
fin.close();
}

     public void sendResponse (int statusCode, String resp, boolean isFile) throws Exception
     {

String statusLine = null;
String serverdetails = "Server: Java HTTPServer";
String contentLengthLine = null;
String fileName = null;
String contentTypeLine = "Content-Type: text/html" + "\r\n";
FileInputStream fin = null;

/* expand this code by providing a handler for each of the error codes above - this example only handles
    error code 200 success, 404 file not found, and 400 bad request  */

if (statusCode == 200) {
statusLine = "HTTP/1.1 200 OK" + "\r\n";
}
else if (statusCode == 404){
statusLine = "HTTP/1.1 404 Not Found" + "\r\n";
}
else {
statusLine = "HTTP/1.1 400 Bad Request" + "\r\n";
}

/* expand this if loop to add support for additional file extensions. */

         if (isFile)
         {
fileName = "c:" + "\\" + resp;
//System.out.println("fName: " + fileName);
fin = new FileInputStream(fileName);
System.out.println("isThere: " + fin.available());
contentLengthLine = "Content-Length: " + Integer.toString(fin.available()) + "\r\n";
if (!fileName.endsWith(".htm") && !fileName.endsWith(".html"))
   contentTypeLine = "Content-Type: \r\n";
if (fileName.endsWith(".jpg"))
   contentTypeLine = "Content-Type: image/jpeg\r\n";
if (fileName.endsWith(".gif"))
   contentTypeLine = "Content-Type: image/gif\r\n";
if (fileName.endsWith(".bmp"))
   contentTypeLine = "Content-Type: image/bmp\r\n";
if (fileName.endsWith(".txt"))
   contentTypeLine = "Content-Type: text/html\r\n";
if (fileName.endsWith(".exe"))
   contentTypeLine = "Content-Type: application/octet-stream";
if (fileName.endsWith(".wav"))
   contentTypeLine = "Content-Type: audio/x-wav";

System.out.println("Setting ContentTypeLine To: " + contentTypeLine);
}
else
{
           resp = myHTTPServer.HTML_START + resp + myHTTPServer.HTML_END;
           contentLengthLine = "Content-Length: " + resp.length() + "\r\n";
    }

outToClient.writeBytes(statusLine);
outToClient.writeBytes(serverdetails);
outToClient.writeBytes(contentTypeLine);
outToClient.writeBytes(contentLengthLine);
outToClient.writeBytes("Connection: close\r\n");
outToClient.writeBytes("\r\n");

if (isFile) sendFile(fin, outToClient);
         else outToClient.writeBytes(resp);

outToClient.close();
}

/*start the listener - can also implement this with worker threads */

     public void run()
     {

try {

conn.getInetAddress();
conn.getPort();


inFromClient = new BufferedReader(new InputStreamReader (conn.getInputStream()));
outToClient = new DataOutputStream(conn.getOutputStream());

String request = inFromClient.readLine();
String header = request;
System.out.println("-------");
System.out.println("Thread PID: " + this.getId() );
System.out.println("Server Received: " + header);
StringTokenizer tok = new StringTokenizer(header);
String httpMeth = tok.nextToken();
System.out.println("METHOD: " + httpMeth);
String httpQuery = tok.nextToken();

StringBuffer response = new StringBuffer();

/* customize your own response message here !! */

response.append("Hello!!");
response.append("Goodbye");
response.append("RFC2616 HTTP Spec");
response.append("Sample Web Server Code");
response.append("By Swati Kher
");



while (inFromClient.ready())
{
response.append(request + "
");
System.out.println(request);
    request = inFromClient.readLine();
}

              /** http://www.w3.org/Protocols/rfc2616/rfc2616.html **/
              /** Response Message - refer to rfc2616 for more information!! **/
if (httpMeth.equals("GET"))
{
                if (httpQuery.equals("/"))
                {
 //sendResponse(HTTP_OK, "SWATI KHER PAGE", false);
 sendResponse(HTTP_OK, response.toString(), false);
   }
   else
   {
String fileN = httpQuery.replaceFirst("/", "");
fileN = URLDecoder.decode(fileN);
fileN = "\\" + fileN;
System.out.println("Send File: " + fileN);
//System.out.println("Found: " + (new File(fileN).isFile()));
if (new File(fileN).isFile()) {
sendResponse(HTTP_OK, fileN, true);
   }
else {
sendResponse(HTTP_BAD_REQUEST, "404 Requested file not found", false);
}
}
}
else
{
   sendResponse(HTTP_NOT_FOUND, "400 Resource not found", false);
}

} catch (Exception e)
{
e.printStackTrace();
}
}


     public static void main(String[] args) throws Exception {

ServerSocket Serv = new ServerSocket (5000, 10, InetAddress.getByName("127.0.0.1"));
System.out.println("Server is listening on port 5000...");

while (true) {
 Socket con = Serv.accept();
 (new myHTTPServer(con)).start();
 }
}
}

Saturday, June 23, 2012

Novel : The Demon Slayer

So this is a great novel about a young boy who has encounters with the supernatural. It's currently available on amazon as e-reader: http://www.amazon.com/dp/B008C909TS

Sunday, June 17, 2012

Happy Father's Day!

Each father's day, I reminisce about the great times I shared with my dad. On this day, whether I was at home with him, or miles away separated by oceans and continents, I never forgot about all the reasons that made him the greatest dad in the world. It has made me the person I am today. When I stop and think about my values, beliefs, hobbies, and habits, I realize that he played a strong role in shaping not just each of my thoughts and actions, but he also gave me my vision and the ability to judge a person and to see the world in its true colors.

In celebration of father's day, here are two great poems:

1. Free Verse about a father's love: http://voices.yahoo.com/free-verse-fathers-love-10931188.html?cat=47

2. Haiku (actually Senryu) about Father's Dayhttp://voices.yahoo.com/about-fathers-day-haiku-11369436.html?cat=42

Saturday, May 12, 2012

Photo Albums

  • I used to store all my digital pics on Yahoo! Photos which was bought by Sharpcast Photos.
  • Sharpcast is now Sugar Sync and the photo album application has been obsoleted by Hummingbird.
  • I now use Flickr for all my photo editing and storage.
  • Here's a great album comparing various online photo albums: http://voices.yahoo.com/best-photo-album-software-programs-7605028.html?cat=15
  • Check out my photos on Flickr: here

Sunday, March 25, 2012

Friday, March 23, 2012

Comparison of Infininand vs Gigabit Ethernet (GigE)

The great debate between Infiniband vs GigE has been ongoing and accelerated by arrival of 10GigE.These are some studies that compare the two protocols. While one is sockets based and the other is qpairs based, these high performance computation-heavy benchmarks stress test for latency, and bandwidth analysis. The results are surprisingly indicative of the type of workload that is running using each interconnect technology.

http://www.deskeng.com/articles/aaammw.htm

Fluent Benchmark Configuration for Infiniband and GigE

LS-DYNA Benchmark comparison published for the LS-DYNA Conference
http://www.dynalook.com/international-conf-2008/

"Optimizing LS-DYNA® Productivity in Cluster Environments"
http://www.dynalook.com/international-conf-2008/ComputingTechnology-3.pdf

Client Code to Create ATM SVC

This is client code that creates Switched Virtual Connection with AAL5 UBR sockets using ATM on Linux distribution from sourceforge.net



#define MAX_SDU     20000
#define MAX_OFFSET  8

void usage(char *name)
{
  fprintf(stderr,"usage: %s [vpi] [vci]\n",name);
  exit(1);
}

int main(int argc, char *argv[])
{
  struct sockaddr_atmsvc to_addr;
  struct atm_blli        blli;
  struct atm_qos         qos, to_qos;
  struct atm_sap         to_sap;
  fd_set                 rd, wd, ed;
  int                    to_fd;
  char                   command[20] = "";
  int                    compare = 1;
  int                    num;

  char   *quit = "q";
  char   *dest = "47.0005.80.ffe100.0000f21a26d8.0020ea000ee0.00";

  /*char   *dest = "nestor-atm";
  */
 
  printf("client: creating new socket...\n");
  if ((to_fd = socket(PF_ATMSVC, SOCK_DGRAM, ATM_AAL5)) < 0)
  {
    perror("client:socket create error\n");
    return 1;
  }
  printf("socket id:");
  printf("%d",to_fd);
  printf("\n");

  printf("client: setting qos...\n");
  memset(&qos,0,sizeof(qos));
  qos.aal = ATM_AAL5;
  qos.txtp.traffic_class = qos.rxtp.traffic_class = ATM_UBR;
  qos.txtp.max_sdu = qos.rxtp.max_sdu = MAX_SDU;

  if (setsockopt(to_fd,SOL_ATM,SO_ATMQOS,&qos,sizeof(qos)) < 0)
  {
        perror("client: setsockopt SO_ATMQOS\n");
        return 1;
  }

  printf("client: setting sap parameters...\n");
  memset(&to_sap,0, sizeof(to_sap));
  if (setsockopt(to_fd, SOL_ATM, SO_ATMSAP,&to_sap, sizeof(to_sap)) <0)
  {
    perror("client: sap paremeter set failed\n");
    close(to_fd);
    return 1;
  }
 

  memset(&to_addr,0, sizeof(to_addr));
  to_addr.sas_family = AF_ATMSVC;
  text2atm(dest, (struct sockaddr *)&to_addr, sizeof(to_addr), T2A_SVC | T2A_LOCAL);

   printf("client: calling connect...\n");
    if (connect(to_fd,(struct sockaddr *) &to_addr,sizeof(to_addr)) < 0)
    {
        perror("client: bind failed\n");
        close(to_fd);
        return 1;
    }
 
    srandom(0); /* we want it to be deterministic */


    FD_ZERO(&rd);
    FD_ZERO(&wd);
    FD_ZERO(&ed);
    FD_SET(to_fd, &wd);
   
    printf("\n");
    printf("Enter message, q to quit: ");
    gets(command);
    compare = strcmp(command, quit);

    while (compare!=0)
    {
      printf("\n");
      printf("client sending message...\n");
     
      num = write(to_fd,command,sizeof(command));
      if (num < 0)
      {
        perror("client: write failed\n");
        close(to_fd);
        return 0;
      }

      printf("\n");
      memset(command,0,sizeof(command));
      printf("Enter message, q to quit: ");
      gets(command);
      compare= strcmp(command, quit);
    }
    printf("Shutting down...!\n");
    shutdown(to_fd, 2);
    printf("Goodbye!\n");
    close(to_fd);
  return 0;
}

Server Code to Create ATM SVC

This code creates ATM Switched Virtual Connection with AAL5 UBR socket using ATM on Linux distribution from sourceforge.net




#define MAX_SDU     20000
#define MAX_OFFSET  8

void usage(char *name)
{
  fprintf(stderr,"usage: %s [vpi] [vci]\n",name);
  exit(1);
}

int main(int argc, char *argv[])
{
  struct sockaddr_atmsvc frm_addr, lsn_addr;
  struct atm_blli        blli;
  struct atm_qos         qos, fm_qos;
  struct atm_sap         lstn_sap;
  socklen_t              fm_len, lsn_len;
  fd_set                 rd, wd, ed;
  int                    lsn_fd, fm_fd;
  int                    pid, lst;
  static unsigned char   buffer[20];
  int                    num;

  /*char   *lstn = "47.0005.80.ffe100.0000.f21a.26d8.0020ea000ee0.00";
  */
  char *lstn = "nestor-atm";
 
  printf("server: creating listen socket...\n");
  if ((lsn_fd = socket(PF_ATMSVC, SOCK_DGRAM, ATM_AAL5)) < 0)
  {
    perror("makeConn:socket error\n");
    return 1;
  }
  printf("socket id:");
  printf("%d",lsn_fd);
  printf("\n");

  printf("server: setting listen qos...\n");
  memset(&qos,0,sizeof(qos));
  qos.aal = ATM_AAL5;
  qos.txtp.traffic_class = qos.rxtp.traffic_class = ATM_UBR;
  qos.txtp.max_sdu = qos.rxtp.max_sdu = MAX_SDU;

  if (setsockopt(lsn_fd,SOL_ATM,SO_ATMQOS,&qos,sizeof(qos)) < 0)
  {
        perror("server: setsockopt SO_ATMQOS\n");
        return 1;
  }

  printf("server: setting listen sap...\n");
  memset(&lstn_sap,0, sizeof(lstn_sap));
  if (setsockopt(lsn_fd, SOL_ATM, SO_ATMSAP,&lstn_sap, sizeof(lstn_sap)) <0)
  {
    perror("server: sap paremeter set failed\n");
    close(lsn_fd);
    return 1;
  }

  memset(&lsn_addr,0, sizeof(lsn_addr));
  lsn_addr.sas_family = AF_ATMSVC;
  text2atm(lstn, (struct sockaddr *)&lsn_addr, sizeof(lsn_addr), T2A_SVC | T2A_LOCAL);

   printf("server: binding listen socket...\n");
    if (bind(lsn_fd,(struct sockaddr *) &lsn_addr,sizeof(lsn_addr)) < 0)
    {
        perror("server: bind failed\n");
        return 1;
    }
 
   fm_len = sizeof(frm_addr);
   memset(&frm_addr,0,fm_len);

    printf("server: listening...\n");
    if (listen(lsn_fd, 3) < 0)
    {
       perror("server: listen failed\n");
       close(lsn_fd);
       return 1;
    }
    srandom(0); /* we want it to be deterministic */
 
  while(1)
  {

    FD_ZERO(&rd);
    FD_ZERO(&wd);
    FD_ZERO(&ed);
    FD_SET(lsn_fd, &rd);
    select(lsn_fd+1, &rd, &wd, &ed, NULL);
   
    printf("server: accepting on new socket...\n");
    fm_fd = accept(lsn_fd, (struct sockaddr *)&frm_addr,&fm_len);
    if (fm_fd < 0)
    {
      perror("server: did not accept\n");
      close(fm_fd);
      close(lsn_fd);
      exit(1);
    }

    while(1)
    {
      FD_SET(fm_fd, &rd);
      select(fm_fd+1, &rd, &wd, &ed, NULL);
      memset(buffer,0,sizeof(buffer));
      printf("server: waiting...\n");
      lst = read(fm_fd,buffer,sizeof(buffer));
      if (lst < 0)
      {
        perror("server: listen error\n");
        close(lsn_fd);
        close(fm_fd);
        exit(0);
      }
      if (lst > 0)
      {
        printf("server: received bytes %d\n", lst);
        printf("server: message = %s\n", buffer);
      }
      if (lst == 0)
      {
       printf("server: closing connection...\n");
       close(lsn_fd);
       close(fm_fd);
       exit(0);
      }
    }
  }
  return 0;
}

Client Code to Create ATM PVC Connection and Data Transfer

 An ATM client here opens a connection for PVC over VPI/VCI = 0/64 defining qos using AAL5 UBR Traffic descriptors using ATM on Linux distribution from sourceforge.net




#define MAX_SDU     20000
#define MAX_OFFSET  8

void usage(char *name)
{
  fprintf(stderr,"usage: %s [vpi] [vci]\n",name);
  exit(1);
}

int main(int argc, char *argv[])
{
  struct sockaddr_atmpvc addr;
  struct atm_qos         qos;
  int    fd;
  int    pid, lst;
  static unsigned char buffer[20];
  int    num;
  char * test = "Sending test";
  char *quit = "q";
  char command[30]="";
  int  compare = 1;
 
  /*if (argc != 3) {usage(argv[0]);}
  */
  printf("Creating a pvc with vpi/vci 0/64... \n");

  if ((fd = socket(PF_ATMPVC, SOCK_DGRAM, 0)) < 0)
  {
    perror("socket error");
    return 1;
  }
  printf("created socket with id: ");
  printf("%d",fd);
  printf("\n");

  memset(&addr,0,sizeof(addr));
  addr.sap_family = AF_ATMPVC;
  addr.sap_addr.itf = 0;
  addr.sap_addr.vpi = 0;
  addr.sap_addr.vci = 64;

  memset(&qos,0,sizeof(qos));
  qos.aal = ATM_AAL5;
  qos.txtp.traffic_class = qos.rxtp.traffic_class = ATM_UBR;
  qos.txtp.max_sdu = qos.rxtp.max_sdu = MAX_SDU;
  if (setsockopt(fd,SOL_ATM,SO_ATMQOS,&qos,sizeof(qos)) < 0)
  {
        perror("setsockopt SO_ATMQOS");
        return 1;
  }
  printf("Set socket options to AAL5, UBR traffic...\n");
  if (bind(fd,(struct sockaddr *) &addr, sizeof(addr)) < 0)
  {
       perror("bind error");
       return 1;
  }
  srandom(0); /* we want it to be deterministic */

    printf("Enter message, q to quit: ");
    gets(command);
  
    compare = strcmp(command, quit);

    while (compare != 0)
    {
      printf("\n");
      printf("client sending message... \n");
      num = write(fd,command, strlen(command));
      printf("client: Bytes sent= %d\n",num);
      if (num<0)
      {
       printf("error no ");
       printf(" %s", strerror(errno));
       return 0;
      }
  
    printf("\n");
    printf("Enter message, q to quit: ");
    gets(command);
    compare = strcmp(command, quit);

    }
   
  return 0;
}

Server Code to Create ATM PVC

This code opens connection on ATM socket defined for PVC on VPI/VCI = 0/64. QOS is defined over AAL5 UBR Traffic using ATM on Linux distribution from sourceforge.net



#define MAX_SDU     20000
#define MAX_OFFSET  8

void usage(char *name)
{
  fprintf(stderr,"usage: %s [vpi] [vci]\n",name);
  exit(1);
}

int main(int argc, char *argv[])
{
  struct sockaddr_atmpvc addr;
  struct atm_qos         qos;
  int    fd;
  int    pid, lst;
  static unsigned char buffer[30];
  int    num;
  char * test = "Sending test";
 
  /*if (argc != 3) {usage(argv[0]);}
  */
  printf("Creating a pvc with vpi/vci 0/64... \n");

  if ((fd = socket(PF_ATMPVC, SOCK_DGRAM, 0)) < 0)
  {
    perror("socket error");
    return 1;
  }
  printf("created socket with id: ");
  printf("%d",fd);
  printf("\n");

  memset(&addr,0,sizeof(addr));
  addr.sap_family = AF_ATMPVC;
  addr.sap_addr.itf = 0;
  addr.sap_addr.vpi = 0;
  addr.sap_addr.vci = 64;

  memset(&qos,0,sizeof(qos));
  qos.aal = ATM_AAL5;
  qos.txtp.traffic_class = qos.rxtp.traffic_class = ATM_UBR;
  qos.txtp.max_sdu = qos.rxtp.max_sdu = MAX_SDU;
  if (setsockopt(fd,SOL_ATM,SO_ATMQOS,&qos,sizeof(qos)) < 0)
  {
        perror("setsockopt SO_ATMQOS");
        return 1;
  }
  printf("Set socket options to AAL5, UBR traffic...\n");
  if (bind(fd,(struct sockaddr *) &addr, sizeof(addr)) < 0)
  {
       perror("bind error");
       return 1;
  }
  srandom(0); /* we want it to be deterministic */

  printf("Server: listening on vc 0,64...\n");
  while (1)
  {
    memset(buffer,0, sizeof(buffer));
    lst = read(fd, buffer, sizeof(buffer));
    if (lst<0)
      perror("server: listen error\n");
    if (lst > 0)
    {
      printf("Server: received bytes %d\n", lst);
      printf("server: message received = %s\n", buffer);
    }
  }

  return 0;
}

My Implementation of Simple Reliable Transport Protocol (SRTP)

 This protocol runs above UDP and provides : reliability, retransmissions, acknowledgements, timeouts, and congestion control


#define NUM_DELIMETERS   10
#define MAX_SRTP_HEADER  22
#define MAX_SRTP_PAYLOAD 81
#define MAX_SRTP_PACKET  MAX_SRTP_PAYLOAD + MAX_SRTP_HEADER
#define MAX_NUM_PACKETS  2000
#define MAX_SRTP_STRING  MAX_SRTP_PACKET + NUM_DELIMETERS
  
#define CLOSED        0
#define LISTEN        1
#define SYN_SENT      2
#define SYN_RECVD     3
#define ESTABLISHED   4
#define FIN_WAIT1     5
#define FIN_WAIT2     6
#define CLOSE_WAIT    7
#define LAST_ACK      8
#define TIMER_EXP     9

/*Error Codes */
#define CHKSUM_FAILED  -2

/*Code for Control Field in UDP packet*/

#define ACK   "A"
#define RST   "R"
#define SYN   "S"
#define FIN   "F"
#define DAT   "D"
#define SYN_ACK "Z"
#define RXM   "R"
#define ERR   "E"
#define FIN_ACK "X"
#define DATL  "L"   /* indentifies last segment */
#define PUT   "put"

int conflag;
/*typedef definitions*/
typedef unsigned long  uint32;
typedef unsigned short uint16;
typedef unsigned char  uint8;

typedef struct
{      
       uint16  src_port_num;
       uint16  dest_port_num;
       uint32  seq_num;
       uint32  ack_num;     
       uint16  window_size;
       u_short  cksum;
       char    *contrl_field;
       uint32  reserved;
       char    data[MAX_SRTP_PAYLOAD];
      
}srtp_header;

typedef struct
{
     srtp_header   pkt;
     bool          received;
     bool          ack_sent;
}incoming_buff;

incoming_buff server_buff[2000];

typedef struct

      srtp_header     pkt;
      int             num_rxmt;
      bool            ack_recd;
      bool            sent_pkt;
      bool            timed_out;
      bool            no_pkt;
      int             pID;
     
}timer;

timer t1[MAX_NUM_PACKETS];

typedef struct
{
       int                start_index;
       int                current_index;
       int                window_size;          
}sWindow;
 
sWindow window; 
   
typedef struct
{
       int                connection_number;
       int                portNumber;
       int                socketDesc;
       int                currentState;
       struct sockaddr_in host_addr;
      
}connection;

connection connS, connC; 

//---------------------------------------------------------------------

void sendPackets(int , int);
srtp_header initialize(void);


void initWindow(int size)

   extern sWindow window;

   window.start_index = 0;
   window.current_index = size-1;
   window.window_size = size;
   //printf("INITIALIZED WINDOW!\n");
return;
}

void initTimer()
{
  extern timer t1[MAX_NUM_PACKETS];
 
  for (int i=0;i
  {  srtp_header srt;
     srt = initialize();
     t1[i].pkt = srt;
     t1[i].ack_recd = 0;
     t1[i].timed_out = 0;
     t1[i].pID = 0;
     t1[i].no_pkt=1;
  }

}

void initializeBuff()
{  extern incoming_buff server_buff[2000];

  for(int i=0;i<2000;i++)
  {  srtp_header srp;
     srp = initialize();
 
     server_buff[i].received=0;
     server_buff[i].pkt = srp;
     server_buff[i].ack_sent=0;
  }
  return; 
}



void insertTimer(srtp_header hdr, int sent)
{
   extern timer t1[MAX_NUM_PACKETS];
   extern sWindow window;
   extern connection connC;

   if (sent
   {
     t1[sent].pkt = hdr;
     printf("INSERTED PACKET! %d %s \n",sent, hdr.contrl_field);
     t1[sent].num_rxmt = 0;
     t1[sent].ack_recd = 0;
     t1[sent].sent_pkt = 0;
     t1[sent].timed_out = 1;
     t1[sent].no_pkt=0;
     t1[sent].pID = 0;
   }
   return;
}

//---------------------------------------------------------------------
u_short checksum(srtp_header srtp)
{
    int sum, i = 0;
    u_short answer;
   
    sum = 0;
    i = 0;
    sum  = sum + srtp.src_port_num;
    //printf("SUM1 = %d\n\n", sum);
    sum  = sum + srtp.dest_port_num;
    //printf("SUM2 = %d\n\n", sum);
    sum  = sum + srtp.seq_num;
    //printf("SUM3 = %d\n\n", sum);
    sum  = sum + srtp.ack_num;
    //printf("SUM4 = %d\n\n", sum);
    sum  = sum + srtp.window_size;
    //printf("SUM5 = %d\n\n", sum);
    sum  = sum + atoi(srtp.contrl_field);
    //printf("SUM6 = %d\n\n", sum);
    sum  = sum + srtp.reserved;
    //printf("SUM7 = %d\n\n", sum);
   
    for(i=0; i
    {
        sum  = sum + (srtp.data[i]);
        //cout<<"SUM "<<<" = "<<<" : "<<<
    }
   
    //printf("SUM8 = %d\n\n", sum);
   
   
    answer = ~sum;  /*takes the ones complement */
    //printf("ANSWER = %d\n\n", answer);
    return answer;
   
}

  /* reverse string s in place*/
  void reverse (char s[])
  {
      int c, i, j;

      for (i=0, j = strlen(s)-1; i
          c = s[i];
          s[i] = s[j];
          s[j] = c;
      }
  }  /* end of reverse*/


  /* converts n to characters in s */
  void itoa(int n, char s[])
  {
      int i, sign;

      if ((sign = n) < 0) {
          n = -n;
      }
      i=0;
      do {
          s[i++] = n % 10 + '0';
      } while ((n /= 10) > 0  );
      if (sign < 0) {
          s[i++] = '-';
      }
      s[i] = '\0';
      reverse(s);
  }   /* end of itoa */

  /* create packet  and place into circular buffer*/
char* getPacket(srtp_header srtp)
  {
     /*declarations*/
    char tmp_str[MAX_SRTP_PACKET + 10]; /*0416*/

    int i,j, k;
   
    static char *out;
    out = (char *)calloc(532, sizeof(char));
    const char *delimiter = "&";
    const char *delnull = "\0"; /*0416*/

    memset(tmp_str, NULL, sizeof(tmp_str) );
   
  
  
    printf("reading the input ...\n\n");

    /**************create header string**********************/
    strcat(out, delimiter);
    itoa(srtp.src_port_num, tmp_str);
    strcat(out, tmp_str);
    strcat(out, delimiter);

    itoa(srtp.dest_port_num, tmp_str);
    strcat(out, tmp_str);
    strcat(out, delimiter);
   
    itoa(srtp.seq_num, tmp_str);
    strcat(out, tmp_str);
    strcat(out, delimiter);

    itoa(srtp.ack_num, tmp_str);
    strcat(out, tmp_str);
    strcat(out, delimiter);

    itoa(srtp.window_size, tmp_str);
    strcat(out, tmp_str);
    strcat(out, delimiter);
   
    itoa(srtp.cksum, tmp_str);
    strcat(out, tmp_str);
    strcat(out, delimiter);
  
    strcat(out, srtp.contrl_field);
    strcat(out, delimiter);
   
    itoa(srtp.reserved, tmp_str);
    strcat(out, tmp_str);
    strcat(out, delimiter);

   
    strncpy(tmp_str, srtp.data, MAX_SRTP_PAYLOAD);
    strcat(out, tmp_str);
    strcat(out, delnull); /*0416*/
    //strcat(out, delimiter);
 
   

    printf("packet string  = %s\n\n", out);
   
    return out;
 
   

  } /* end of getPacket()*/


  /* parse packet into tokens */
srtp_header parser(char s[])
  {
    /*declarations */
    srtp_header srtp;
    const char *delimiter = "&";
    int i;
    char *data;
    data = (char *)calloc(MAX_SRTP_PAYLOAD, sizeof(char)); /*0416*/
    memset(data, NULL, MAX_SRTP_PAYLOAD); /*0416*/
    const char *delnull = "\0"; /*0416*/

   
   
   
    printf("You are inside Parser\n\n");

    /**************parse string********/
   
    srtp.src_port_num = (short)atoi(strtok(s, delimiter)); 
    srtp.dest_port_num = (short)atoi(strtok(NULL, delimiter));
    srtp.seq_num = (short)atoi(strtok(NULL, delimiter));
    srtp.ack_num = (short)atoi(strtok(NULL, delimiter));
    srtp.window_size = (short)atoi(strtok(NULL, delimiter));
    srtp.cksum = (u_short)atoi(strtok(NULL, delimiter));
    srtp.contrl_field = (strtok(NULL, delimiter) );
    srtp.reserved = (short)atoi(strtok(NULL, delimiter));
 
    //data = strtok(NULL, delimiter);
    data = strtok(NULL, delnull); /*0416*/

    
    if(data != NULL)
    {
      strncpy(srtp.data, data, MAX_SRTP_PAYLOAD); /*0416*/
    }
    

  

    /*printf("src_port_num = %d\n", srtp.src_port_num);
    printf("dest_port_num = %d\n", srtp.dest_port_num);
    printf("cksum_num = %d\n", srtp.cksum);
    printf("seq_num = %d\n", srtp.seq_num);
    printf("ack_num = %d\n", srtp.ack_num);
    printf("contrl_field = %s\n", srtp.contrl_field);*/
    if(data != NULL)
    {
      printf("data = %s\n", data);
    }
   
    printf("Leaving Parser\n\n");
   
    return srtp;

    /*************parse string**********/


  }  /* end of parser */
 
 
 
/* initializes srtp struct to its default values */
srtp_header initialize(void)
{
   
    srtp_header packet;
  
    packet.src_port_num = 0;
    packet.dest_port_num = 0;
    packet.seq_num = 0;
    packet.ack_num = 0;
    packet.cksum = 0;
    packet.contrl_field = "0";
    packet.window_size = 0; 
    packet.reserved = 0;
    memset(packet.data, 0, MAX_SRTP_PAYLOAD );
   
    //printf("You have initialized the packet\n\n");
   
    return packet;

} /* end of initialize */

int cTimer(int index,int amount)
{
   extern timer t1[MAX_NUM_PACKETS];
   int procId;
  
   procId = fork();
  
   switch(procId)
   {
     case 0:
        printf("Timer %d started!\n", index);
        //usleep(amount);/*0418*/
    sleep(amount);
    printf("Timer %d timer expired!\n", index);
   
    _exit(0);
    
     default:
       t1[index].pID = procId;
       //printf("TIMER PID = %d\n", procId);
       return procId;
   }
  
}


void sendPackets(int startIx, int numberOfPkts)
{  extern timer t1[MAX_NUM_PACKETS];
   extern int conflag;
   int r,i, slp, numTrmt;

   if ((startIx+numberOfPkts-1)>MAX_NUM_PACKETS)
        numTrmt = MAX_NUM_PACKETS;
   else numTrmt = startIx+numberOfPkts-1;

     
   //if ((t1[startIx].num_rxmt < 3)&&(t1[startIx].timed_out))
   //{  
  
      for (i=startIx;i<=(numTrmt);i++)
      {
        if((!t1[i].no_pkt)&&(t1[i].num_rxmt<3)&&(t1[i].timed_out))
        { t1[i].ack_recd = 0;
          t1[i].timed_out=0;  

      slp = cTimer(i,10);/*0418*/

          r = sendto(connC.socketDesc,getPacket(t1[i].pkt),MAX_SRTP_STRING,0,(struct sockaddr*)&connC.host_addr, sizeof(struct sockaddr));
     
          if (r==-1)
          {
           //printf("sendto fails\n");
       return;
          }
          else if (t1[i].sent_pkt)
          {
           t1[i].num_rxmt++;
       printf("REXMT PACKET %d FOR %d TIME!!\n", i, t1[i].num_rxmt);
          }
          else 
      {
       t1[i].num_rxmt = 0;
           t1[i].sent_pkt = 1;
           printf("=====PACKET %d SENT====\n", i);      
      }
     }
     else if((!t1[i].no_pkt)&&(t1[i].num_rxmt==3)&&(t1[i].timed_out))
     {
        printf("pkt %d experienced congestion\n",i);
            conflag = 1;
     }

      }  
   //}
   //else if (t1[startIx].num_rxmt==3)
   //{
   //   printf("**************CONGESTION EXPERIENCED*********\n");
     
   //}
return;  
}


//======================================BEGIN API FOR SRTP=============================================
int sendSynAckPkt()
  {
           int sendsynack;
           srtp_header synackPkt;
       extern connection connS;
       
       synackPkt = initialize();
           synackPkt.contrl_field = SYN_ACK;
           synackPkt.seq_num = rand();
      
           sendsynack = sendto(connS.socketDesc,getPacket(synackPkt),MAX_SRTP_PACKET,0,(struct sockaddr *)&connS.host_addr, sizeof(struct sockaddr));
      
           if (sendsynack == -1)
           {
              return -1;
           }
       else
       {
           return 1;
       }

      
  } /*end of sendSynAckPkt*/
 
 
int sendFinAckPkt()
  {
          int sendfinack;
          extern connection connS;
          srtp_header finackPkt;
      
          finackPkt = initialize();
          finackPkt.contrl_field = FIN_ACK;
          finackPkt.seq_num = rand();
         
          sendfinack = sendto(connS.socketDesc,getPacket(finackPkt),MAX_SRTP_PACKET,0,(struct sockaddr *)&connS.host_addr, sizeof(struct sockaddr));
      
              if (sendfinack == -1)
              {
                 return -1;
              }
              else
          {   
               return 1;
          }
          
    
  } /* end of sendFinAckPkt */
      
 
int s_sendAckPkt(int seq_num)
 {

          int sendAck;
      srtp_header ackPacket;
      extern connection connS;
      ackPacket = initialize();
      ackPacket.contrl_field = ACK;     
      ackPacket.ack_num = seq_num;
     
     
      sendAck = sendto(connS.socketDesc, getPacket(ackPacket), MAX_SRTP_PACKET,0,(struct sockaddr *)&connS.host_addr, sizeof(struct sockaddr));
     
      if (sendAck == -1)
      {
        return -1;
      }
      else
      {
         return 1;

      }
   
 } /* end of s_sendAckPkt */

int sendFinPkt()
 {
         int sendFin;
         extern connection connC;
         srtp_header finPacket;
             finPacket = initialize();
      
             finPacket.seq_num = rand();     
             finPacket.contrl_field = FIN;   
   
         sendFin = sendto(connC.socketDesc, getPacket(finPacket), MAX_SRTP_PACKET, 0, (struct sockaddr *)&connC.host_addr, sizeof(struct sockaddr));
        
         if (sendFin == -1)
             {
               return -1;
             }      
             else
             { 
             return 1;

         }
 } /*end of sendFinPkt */   
   
          
   
  
 int sendSynPkt()
 {

        int  sendSyn;
        extern connection connC;
        srtp_header synPacket;
        synPacket = initialize();
      
        synPacket.seq_num = rand();
        //printf("SYN SEQ NUM = %d\n\n", synPacket.seq_num );
        synPacket.contrl_field = SYN;
        sendSyn = sendto(connC.socketDesc, getPacket(synPacket), MAX_SRTP_PACKET, 0, (struct sockaddr *)&connC.host_addr, sizeof(struct sockaddr));
       
   
    if (sendSyn == -1)
        {
          return -1;
        }
    else
    {
      return 1;
    }
      
 }  /* end of sendsynpkt */

int c_sendAckPkt(int ackNum)
 {

          int sendAck;
      extern connection connC;
      srtp_header ackPacket;
      ackPacket = initialize();
      ackPacket.contrl_field = ACK;     
      ackPacket.ack_num = ackNum;
     
      sendAck = sendto(connC.socketDesc, getPacket(ackPacket), MAX_SRTP_PACKET,0,(struct sockaddr *)&connC.host_addr, sizeof(struct sockaddr));
     
      if (sendAck == -1)
      {
        return -1;
      }
      else
      {
         return 1;

      }
   
 } /* end of c_sendAckPkt */
     

/*** generate one packet that contains command, filename, filesize***/
int sendSetupPkt(char *filename, char *command, int namelength)
{  
        
        int sendPkt;
        srtp_header setupPkt;
        extern connection connC;
       
        setupPkt = initialize();
        setupPkt.contrl_field = command;
        memset(setupPkt.data,0,80);
        strncpy(setupPkt.data, filename, namelength);
        sendPkt = sendto(connC.socketDesc, getPacket(setupPkt), MAX_SRTP_PACKET+10, 0, (struct sockaddr*)&connC.host_addr, sizeof(struct sockaddr));
        if(sendPkt ==-1)
        {
            return -1;  /* error sending packet */
        }
        else
        {
            return 1;  /* packet sent ok */
        }
       
} /* end of sendSetupPkt */



//THIS FUNCTION PERFORMS 3-WAY HANDSHAKE, ESTABLISHES   
//CONNECTION AND RETURNS A CONNECTION NUMBER
    
    int SRTP_Open(struct sockaddr *udp_host_addr, int port_number)
    {  int connection_number = 1;
       struct sockaddr_in client_addr;
       extern connection connC;
      
       //*************STEP 1: CREATE SOCKET***********************

    if (connC.currentState ==  CLOSED)
    {
      //printf("Current State = %d\n",connC.currentState);
   
          connC.socketDesc = socket(AF_INET, SOCK_DGRAM, 0);
      connC.connection_number = connection_number = 1;

          client_addr.sin_family      = AF_INET;
          client_addr.sin_port        = htons(port_number);
          client_addr.sin_addr.s_addr = INADDR_ANY;      
             
          if (connC.socketDesc == -1)
          {
           printf("Socket failed to create!\n");
       exit(1);
          }
      
          else
          {  
       //************STEP 2: BIND SOCKET TO LOCAL ADDRESS**********
      
           if (bind(connC.socketDesc, (struct sockaddr *)&client_addr, sizeof(struct sockaddr)) == -1)
       {
          printf("Bind Failed in SRTP_Open!\n");
          close(connC.socketDesc);
          exit(1);
       }
       else
       {
       // printf("Bind successful!\n");
        fcntl(connC.socketDesc,F_SETFL,O_NONBLOCK);
           }
      }
         return connection_number;
     } 
}
   
//********************END SRTP_Open Function***************************
   
//***********STEP 1: GO TO STATE LISTEN************** 
    
int SRTP_Listen(int port_number)       

       //********** LISTEN FOR A SYN*************
       extern connection connS;
       int sockfd;
       struct sockaddr_in host_addr;
      
       connS.connection_number = 2;
      
    if (connS.currentState == CLOSED)
    { 
       //*********CREATE SOCKET**************
      
       sockfd = socket(AF_INET, SOCK_DGRAM, 0);
       connS.socketDesc = sockfd;
      
       host_addr.sin_family = AF_INET;
       host_addr.sin_port   = htons(port_number);
       host_addr.sin_addr.s_addr = INADDR_ANY;
      
       if(sockfd==-1)
       {
          printf("CREATE SOCKET FAILED!\n");
      exit(1);
       }
      
       //************ELSE BIND THE SOCKET*******
       else
       {
          connS.socketDesc = sockfd;
      if(bind(sockfd,(struct sockaddr *)&host_addr, sizeof(struct sockaddr)) == -1)
      {
         printf("Bind failed in SRTP_Listen!\n");
         close(sockfd);
         exit(1);
      }
      else
      {printf("Bind Successful!\n");
       fcntl(sockfd,F_SETFL,O_NONBLOCK);
      }
       }
           
       connS.currentState = LISTEN;
       //printf("Current State: %d\n",connS.currentState);

       return connS.connection_number;
     }
    
     if (connS.currentState == SYN_RECVD)
     { 
       //*************SEND A SYNACK********************
      
        int sendSyn = sendSynAckPkt();
      
      
       if (sendSyn == -1)
       {
          printf("SYNACK SEND ERROR!\n");
      connS.currentState = CLOSED;
      close(connS.socketDesc);
      exit(1);
       }
       else if (sendSyn != -1)
       {
         printf("SYNACK SENT!\n");   
       }
       return connS.connection_number;
      }     
    }

int SRTP_Close(int connection_number)
{
    extern connection connS,connC;
    //printf("INSIDE CLOSE!\n");
   
    if ((connS.connection_number==connection_number)&&(connS.currentState==CLOSE_WAIT))
    {
      //printf("SENDING A FINACK!\n");
      connS.currentState = LAST_ACK;
      int temp = sendFinAckPkt();
      return temp;
    }
    else if((connC.connection_number==connection_number)&&(connC.currentState==ESTABLISHED))
    {
      //printf("TERMINATING-SENDING A FIN\n");
      connC.currentState = FIN_WAIT1;
      int temp = sendFinPkt();
      return temp;
    }
    else if((connC.connection_number==connection_number)&&(connC.currentState==FIN_WAIT2))
    {
       connC.currentState = CLOSED;
       //printf("Sending Ack on FIN\n");
       int temp = c_sendAckPkt(0);
       return temp;
    }
}

int SRTP_Send(int conn_number, char*buffer_ptr, int buffer_size)

    int num, r, sent;
    static char *string;
    string = (char *)calloc(81, sizeof(char));
    srtp_header srtp;
    static char *result;
    char value[81];
    extern connection conn1;
   
   sent = num = 0;
   memset(string, NULL, MAX_SRTP_PAYLOAD + 1);
   memset(value, NULL, 81);
     
   while(*buffer_ptr != 0)
   {
     value[num++] = *buffer_ptr++;
             
     if( ((num / 80) == 1) )
     {
       //printf("String greater than 80\n\n\n\n");

      srtp = initialize();
      srtp.src_port_num = 3490;
      srtp.dest_port_num = connC.portNumber;
      srtp.window_size = 10;
      //srtp.contrl_field = DAT; /*0416*/
      srtp.ack_num = 0;
     
      if(*buffer_ptr == NULL)  /*0416*/
      {
         srtp.contrl_field = DATL;
      }
      else
      {
         srtp.contrl_field = DAT;   
      }

           
       
       srtp.seq_num = (sent+1)*80;
       memset(srtp.data,NULL,80);  
              
       strcat(string, value);
       strncpy(srtp.data, string, strlen(string));
        srtp.cksum = checksum(srtp);
        //printf("~~~~~~CHECKSUM ON THIS PACKET:  %d\n", srtp.cksum);     
         
       insertTimer(srtp,sent);    
       sent++;

       num = 0;
       memset(string, NULL, MAX_SRTP_PAYLOAD + 1);
       memset(value, NULL, 81);
     }   
   } /*end of whileloop */
    
   //printf("strlen = %d\n\n", strlen(value) ) ;
   if (strlen(value)>0)
   {
      //printf("String less than 80\n\n");

     srtp = initialize();
     srtp.src_port_num = 3490;
     srtp.dest_port_num = connC.portNumber;
     srtp.window_size = 10;
     srtp.ack_num = 0;
           
      
      srtp.contrl_field=DATL;
      srtp.seq_num = (sent+1)*80;
      memset(srtp.data,NULL,80);
                   
      strcat(string, value);
      strncpy(srtp.data, string, strlen(string));
      srtp.cksum = checksum(srtp);
      //printf("~~~~~~CHECKSUM ON THIS PACKET: %d\n", srtp.cksum);     
     

      insertTimer(srtp,sent);
      sent++;
      num = 0;
      memset(string, NULL, MAX_SRTP_PAYLOAD + 1);

     } /*end of if*/
         
     return sent;

}


int SRTP_Receive(int conn_num, char *buffer_ptr, int buffer_size)
{
    
     srtp_header srtp;
   
    /*  1) reads data from udp buffer
      2) parse packet string
      3) create data packet (structs)
      4) return # of bytes received or an error code = -1 */
     
      srtp = parser(buffer_ptr);
     
      /*** pass srtp to global buffer if space is avail if not return error **/
      

       return buffer_size;
}