Pages

Subscribe:

Ads 468x60px

Monday, December 24, 2012

fatal error LNK1168: cannot open 'filename.exe' for writing

Hi guys how you all doing?.. I have just finished my University work and having a free week before joining the Industry. Recently I was trying to do some projects using Microsoft Visual C++ 2010 Express in Windows 8 Operating System environment. When I tried to build few solutions I came with the Error called

fatal error LNK1168: cannot open 'filename.exe' for writing

Recently I have disabled some windows services since Some features were slowing down my laptop. Then I realized that I have disabled the Application Experience Service also. 

If you experience the same error go to Start >> Run >> services.msc

Then start the Application Experince Service. That's it. It will solve the error.
 

Friday, November 30, 2012

How to write a Simple Web Server using C

In this post I'm going to explain how to write a simple but functional web server using sockets. First we have to set configuration for our web server and most common way of doing is to put the configurations into a .ini file. I used inih which is a simple .ini parser written in C. source 

Below is a sample .ini file
; Config file for ASK server

[Protocol]             
Version=6              ; IPv6

[Web]
http_version=HTTP/1.1
root_dir = www/
default_page = index.html
error_page = error.html
backlog = 10
max_header_size=1024

[Codes]
200 = OK
404 = Content Not Found

Below is the  askserver.c source file.  First the configurations are loaded and waiting for incoming requests. Then whenever a request is arrived the server check for the file requested. If it is available send a message code 200 and the file type server is going to send to the client. If the requested file was not fond, then send the message code 400 content not found. 
When a available file is send to the client, method is used.

sendfile(destination, source, offset,size);

//******************** askserver.c ******************/
// Aruna Sujith Karunarathna
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/sendfile.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <netinet/tcp.h>
#include <limits.h>
#include <unistd.h>
#include <assert.h>
#include "ini.h"

#define CONFIGURATION_FILE  "configuration/ask.ini"


typedef struct{
    int version;
    int backlog;
	int max_header_size;
    const char* http_version;
    const char* root_dir;
	const char* default_page;
	const char* error_page;
} configuration;
configuration config;

void sigchld_handler(int s){
	while(waitpid(-1, NULL, WNOHANG) > 0);
}

// get sockaddr, IPv4 or IPv6:
void *get_in_addr(struct sockaddr *sa){
	if (sa->sa_family == AF_INET) {
		return &(((struct sockaddr_in*)sa)->sin_addr);
	}
	return &(((struct sockaddr_in6*)sa)->sin6_addr);
}

static int handler(void* user, const char* section, const char* name,const char* value){
    
    configuration* pconfig = (configuration*)user;

    #define MATCH(s, n) strcasecmp(section, s) == 0 && strcasecmp(name, n) == 0
    if (MATCH("protocol", "version")) {
        pconfig->version = atoi(value);   
    } else if (MATCH("web", "http_version")) {
        pconfig->http_version = strdup(value);
    } else if (MATCH("web", "root_dir")) {
        pconfig->root_dir = strdup(value);
    } else if (MATCH("web", "default_page")) {
        pconfig->default_page = strdup(value);
    } else if (MATCH("web", "error_page")) {
        pconfig->error_page = strdup(value);
    } else if (MATCH("web", "backlog")) {
        pconfig->backlog = atoi(value);
    } else if (MATCH("web", "max_header_size")) {
        pconfig->max_header_size = atoi(value);
    } else {
        return 0;  /* unknown section/name, error */
    }
    return 1;
}

char* get_extension(char* file_name){
    char* extension;
    extension = strchr(file_name,'.')+1	; 
    printf("EXTENSION %s \n",extension);
    return extension;
}

char* get_content_type(char* extension){
    char* type;
    if(strcmp(extension,"html")==0)
        type = "text/html";
    else if(strcmp(extension,"css")==0)
        type = "text/css";
    else if(strcmp(extension,"txt")==0)
        type = "application/text";
    else if(strcmp(extension,"pdf")==0)
        type = "application/pdf";
    else if(strcmp(extension,"zip")==0)
        type = "application/zip";    
    else if(strcmp(extension,"xml")==0)
        type = "application/xml";  
    else if(strcmp(extension,"js")==0)
        type = "application/javascript";                  
    else if(strcmp(extension,"jpg")==0)
        type = "image/jpg";
    else if(strcmp(extension,"png")==0)
        type = "image/png";    
    else if(strcmp(extension,"exe")==0)
        type = "application/octet-stream";
    else if(strcmp(extension,"ico")==0)
        type = "image/x-icon";
    else if(strcmp(extension,"php")==0)
        type = "text/html";
        
    printf("TYPE %s ",type);    
    return type;    

}

int set_header(char *header,int status_code,char *file_name,int file_length){
    if(status_code==404){
        //printf("%s %d File Not Found\n",config.http_version,status_code);
        sprintf(header, 
				"%s %d File Not Found\n"					
		     	 "\n",config.http_version,status_code);
		printf("\nHEADER MESSAGE %s \n",header);
        return -1;
    }
	if(status_code==400){
		sprintf(header, 
				"%s %d Bad Request\n"					
		     	 "\n",config.http_version,status_code);
		return -1;
	}
	if(status_code==501){	
		sprintf(header,"%s %d POST Not Implemented\n "
		"\n POST Not Implemented",config.http_version,status_code);	
		return -1;
	}
	char *extension;
	extension = get_extension(file_name);     
	char *content_type;
	content_type = get_content_type(extension);
		
	sprintf(header,"%s %d OK \n"	
	"Content-Type: %s\n"
	"Content-Length: %i\n"
		      "\n",config.http_version,status_code,content_type ,file_length);
	printf("\nHEADER MESSAGE %s \n",header);	      
}

char* check_request(char * request){
	char* ptr;
	ptr = strstr(request," HTTP/");
   // printf("CHK REQUEST %s \n",request);
	if(ptr == NULL)	{
		printf("Not HTTP request\n");
	}else{
	 /* *** HTTP request received *** */

		/* *** check for GET request *** */
		if(strncmp(request,"GET ",4) == 0)	{
			ptr="GET";
		}
		/* *** check for POST request, give 501 error if received *** */
		else if(strncmp(request,"POST ",5) == 0){
			printf("501 Method not implemented\n");
			ptr="POST";
		}
	}

	return ptr; 
}

char* get_path(char *request)
{
	int i=0;
//	printf("REQUEST %s \n",request);
	char *token = NULL;
	token = strtok(request, " ");
	token = strtok(NULL, " ");
	
	return token;
}

int send_content(char* file_name, int socket, int status_code){
    int sent_size; 	
    char header[config.max_header_size];
	int open_file;               /* file descriptor for source file */
    struct stat stat_buf;  /* hold information about input file */
    off_t offset = 0;      /* byte offset used by sendfile */
    int return_code;                /* return code from sendfile */
  
    open_file = open(file_name, O_RDONLY);/* check that source file exists and can be opened */ 
    fstat(open_file, &stat_buf);         /* get size and permissions of the source file */
   
  
	set_header(header,status_code,file_name,(int)stat_buf.st_size);
	sent_size=send(socket, header, strlen(header), 0);
	
	
    /* copy file using sendfile ####################################### */
    // sendfile(destination, source, offset,size);
    return_code = sendfile (socket, open_file, &offset, stat_buf.st_size);
    printf("file size %d Bytes \n\n",return_code);
    
    if (return_code == -1) {
        fprintf(stderr, "error from sendfile: %s\n", strerror(errno));
 	}
 	else if (return_code != stat_buf.st_size) {
        fprintf(stderr, "incomplete transfer from sendfile: %d of %d bytes\n", return_code, (int)stat_buf.st_size); 
    }
    /* clean up and exit */
    close(socket);
    close(open_file);
    return 0;

}

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

        if (ini_parse(CONFIGURATION_FILE , handler, &config) < 0) {
                printf("Can't load 'ask.ini'\n");
                return 1;
        }
         printf("Config loaded from 'ask.ini':\nversion=%d\nbacklog=%d\nmax_header_size=%d \nhttp_version=%s\n",
        config.version, config.backlog, config.max_header_size, config.http_version);
        
	int sockfd, new_fd;  // listen on sock_fd, new connection on new_fd
	struct addrinfo hints, *servinfo, *p;
	struct sockaddr_storage their_addr; // connector's address information
	socklen_t sin_size;
	struct sigaction sa;
	int yes=1;
	char s[INET6_ADDRSTRLEN];
	int rv;

	memset(&hints, 0, sizeof hints);
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_flags = AI_PASSIVE; // use my IP

	if ((rv = getaddrinfo(NULL, argv[1], &hints, &servinfo)) != 0) {
		fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
		return 1;
	}

	// loop through all the results and bind to the first we can
	for(p = servinfo; p != NULL; p = p->ai_next) {
		if ((sockfd = socket(p->ai_family, p->ai_socktype,
				p->ai_protocol)) == -1) {
			perror("server: socket");
			continue;
		}

		if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes,
				sizeof(int)) == -1) {
			perror("setsockopt");
			exit(1);
		}

		if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
			close(sockfd);
			perror("server: bind");
			continue;
		}

		break;
	}

	if (p == NULL)  {
		fprintf(stderr, "server: failed to bind\n");
		return 2;
	}

	freeaddrinfo(servinfo); // all done with this structure

	if (listen(sockfd, config.backlog) == -1) {
		perror("listen");
		exit(1);
	}

	sa.sa_handler = sigchld_handler; // reap all dead processes
	sigemptyset(&sa.sa_mask);
	sa.sa_flags = SA_RESTART;
	if (sigaction(SIGCHLD, &sa, NULL) == -1) {
		perror("sigaction");
		exit(1);
	}

	printf("ASK_SERVER: waiting for connections...\n");

	while(1) {  // main accept() loop
		sin_size = sizeof their_addr;
		new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
		if (new_fd == -1) {
			perror("accept");
			continue;
		}

		inet_ntop(their_addr.ss_family,get_in_addr((struct sockaddr *)&their_addr),s, sizeof s);
		printf("ASK_SERVER: got connection from %s\n", s);

		if (!fork()) { // this is the child process
			close(sockfd); // child doesn't need the listener
			int buffer_size =1024;
			char* char_buffer = malloc(buffer_size);
			//get the client request
			read(new_fd,char_buffer,buffer_size);
			char *path;
  		    //printf("REQUEST ------ %s \n",char_buffer);
			//printf("CHECK_REQUEST %s \n",check_request(char_buffer));
			char* request_type = check_request(char_buffer);
			printf("REQUEST TYPE ::::::: %s\n",request_type);
			char* header=malloc(200);
  		    memset(header,0,200);
            
            if(request_type==NULL){	  	
  			    set_header(header,400,NULL,0);
  			    send(new_fd, header, strlen(header), 0);
  			    return 0;
  			}
  		    else if(strcmp(request_type,"POST")==0){
  			    set_header(header,501,NULL,0);
  			    send(new_fd, header, strlen(header), 0);
  			    return 0;
  		    }   
  		    
  		    path = get_path(char_buffer);
  		    if(strcmp("/",path)==0){
  		        path = (char*)config.default_page;
  		        // path = config.default_page;
  		    }
  		    char *root_dir=malloc(100);
			memset(root_dir,0,sizeof root_dir);
			strcpy(root_dir,config.root_dir);			
			path=strcat(root_dir,path);
			//printf("11111111111 real %s \n", path);
			
			/* ******* REQUEST FILE FOUND ********** */
  		    if(access(path, F_OK ) != -1){
				 send_content(path,new_fd,200);
				 //printf("OKKKKKKKKK %s \n", path);
			}
  		    else{					
				memset(root_dir,0,100);
				strcpy(root_dir,config.root_dir);
				path=strcat(root_dir,"/");
				path=strcat(root_dir,config.error_page);
				//printf("ERRRRRRRRRRORRR %s \n",path);
				send_content(path,new_fd,404);	
			}
  		    
			
		//	if (send(new_fd, "Hello, world!", 13, 0) == -1)
		//		perror("send");
		    free(char_buffer);
			close(new_fd);
			exit(0);
		}
		close(new_fd);  // parent doesn't need this
	}	
	
        printf("Config loaded from 'ask.ini': version=%d, backlog=%d,max_header_size=%d ,  http_version=%s\n",
        config.version, config.backlog, config.max_header_size, config.http_version);
        return 0;
		
}

I have included a sample www folder in the same directory to simulate the web server.

Download the full project from here.... DOWNLOAD

How to Test the Sample ASK Server.

Open a Terminal and Type the Following Commands.

[aruna@ubuntu]~$ makefile

[aruna@ubuntu]~$ ./askserver 7788


The argument 7788 is the port that we bind the webserver. Now open a web browser and type the following address localhost:7788

You'll see the web server is up and running. :)

Wednesday, October 24, 2012

Network Simulation using NS2

Before deploying a network it is necessary to check how the network would behave after the deployment. After deploying the network sometime it may not function/behave as expected. So it is better to get some idea before the real deployment. 

There are commercial simulators of course,  but the problem is that they are very expensive. So NS2 come in handy, since it's free and opensource. The script files you write in NS2 is .tcl 

First of all you have to install NS2 in your computer. Just enter the following command and it will be installed.

[aruna@ubuntu]~$ sudo apt-get install ns2 nam

Now you have installed NS2. (I am not going to teach you how to write .tcl scripts there are enough tutorials on how to write .tcl scripts. I just want to give you a simple introduction to what is NS2 and what it is capable of.)
The following code creates six nodes 0,1,2,3,4 and 5 and there are two tcp connections from node 0 to 5 and the other from node 1 to 4. You can see how the data packet travel through the links and even you can analyze each data packet.

Download Code Link :   Download 

#**********************************************************************
 # Sample tcp.tcl file 
#*********************************************************************/


#Create a simulator object
set ns [new Simulator]

$ns color 1 Blue
$ns color 2 Red
$ns color 3 Green

#Open the nam trace file
set nf [open out.nam w]
$ns namtrace-all $nf

#Define a 'finish' procedure
proc finish {} {
        global ns nf f0 f1
        $ns flush-trace
 #Close the trace files
        close $nf
 #Execute nam on the trace file
        exec nam out.nam &
        exit 0
}
#Create two nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]

#Create a duplex link between the nodes
$ns duplex-link $n0 $n2 1Mb 10ms DropTail 
$ns duplex-link $n1 $n2 1Mb 10ms DropTail 
$ns duplex-link $n2 $n3 1Mb 10ms DropTail 
$ns duplex-link $n3 $n4 1Mb 10ms DropTail 
$ns duplex-link $n3 $n5 1Mb 10ms DropTail 

#give node position
$ns duplex-link-op $n0 $n2 orient right-down 
$ns duplex-link-op $n1 $n2 orient right-up 
$ns duplex-link-op $n2 $n3 orient right 
$ns duplex-link-op $n3 $n4 orient right-up 
$ns duplex-link-op $n3 $n5 orient right-down

#Create a TCP agent and attach it to node n0
set tcp0 [new Agent/TCP]
$ns attach-agent $n0 $tcp0
set sink0 [new Agent/TCPSink]
$ns attach-agent $n5 $sink0
$ns connect $tcp0 $sink0
$tcp0 set fid_ 3

#Create a TCP agent and attach it to node n1
set tcp1 [new Agent/TCP]
$ns attach-agent $n1 $tcp1
set sink1 [new Agent/TCPSink]
$ns attach-agent $n4 $sink1
$ns connect $tcp1 $sink1
$tcp1 set fid_ 2

# Create a CBR traffic source and attach it to tcp1
set ftp0 [new Application/FTP]
$ftp0 set packetSize_ 500
$ftp0 set interval_ 0.005
$ftp0 attach-agent $tcp1
$ftp0 set rate_ 3mb
$ftp0 set random_ false

# Create a CBR traffic source and attach it to tcp0
set ftp1 [new Application/FTP]
$ftp1 set packetSize_ 500
$ftp1 set interval_ 0.005
$ftp1 attach-agent $tcp0
$ftp1 set rate_ 3mb
$ftp1 set random_ false

#Schedule events for the CBR agent
$ns at 0.0 "$ftp0 start"
$ns at 1.0 "$ftp1 start"
$ns at 5.0 "$ftp0 stop"
$ns at 5.0 "$ftp1 stop"

#Call the finish procedure after 5 seconds of simulation time
$ns at 5.0 "finish"

#Run the simulation
$ns run
To run the following code just type 

[aruna@ubuntu]~$ ns tcp.tcl



Hope you'll enjoy NS2... :)

Sunday, August 26, 2012

Longest Path Algorithm (Java Code)

The longest path algorithm is used to find the maximum length of a given graph. The maximum length may be measured by the maximum number of edges or the sum of the weights in a weighted graph. Following is a sample java code to find the Longest Path. It has two classes. CreateMatrix.java class to create the matrix and LongestPath.java to find the Longest Path to the created matrix. 

Download Source From Here.. DOWNLOAD

/********************* LongestPathAlgo.java ********************/ 
class LongestPathAlgo {

    public static void main(String[] args) {

        int length = 13;//length of the 2-D array
        int adjMatrix[][] = new int[length][length];
        CreateMatrix cm = new CreateMatrix();
        cm.createMatrix(length);
        adjMatrix = cm.readMatrix(adjMatrix);

        long starttime = System.nanoTime();
        LongestPathAlgo lpa = new LongestPathAlgo();
        boolean visited[] = new boolean[adjMatrix.length];
        lpa.initialize(adjMatrix, visited);
        int max = lpa.longestPath(0, visited, adjMatrix);
        long runtime = System.nanoTime()-starttime;
        System.out.println("Runtime =" + runtime +" nano seconds");
        System.out.println("Longest Path Length = "+max);
    }

    public void initialize(int adjMatrix[][], boolean visited[]) {
        for (int u = 0; u < adjMatrix.length; u++) {
            visited[u] = false;
        }
    }

    int longestPath(int vertex, boolean visited[], int adjMatrix[][]) {
        int dist, max = 0;
        visited[vertex] = true;

        for (int u = 0; u < adjMatrix[vertex].length; u++) {
            if (adjMatrix[vertex][u] != -1) {
                if (!visited[u]) {
                    dist = adjMatrix[vertex][u] + longestPath(u, visited, adjMatrix);
                    if (dist > max) {
                        max = dist;
                    }
                }
            }
        }
        visited[vertex] = false;
        return max;
    }
}

/********************* CreateMatrix.java ********************/
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;


public class CreateMatrix {

    public void createMatrix(int length) {
        Random ran = new Random();
        FileWriter fw;
        try {
            File file = new File("matrix.txt");
            fw = new FileWriter(file);
            BufferedWriter bw = new BufferedWriter(fw);
            for (int i = 0; i < length; i++) {
                for (int j = 0; j < length; j++) {
                    if (i == j) {
                        bw.write("" + -1);
                    } else {
                        bw.write("" + (i+j));
                    }
                    bw.write("@");
                }
                bw.newLine();
            }
            for (int i = 0; i < length; i++) {
            }
            bw.close();
            fw.close();
        } catch (IOException ex) {
            System.out.println("File Not Found");
          }

    }

    public int[][] readMatrix(int adjMatrix[][]) {

        try {
            File file = new File("matrix.txt");
            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader(fr);
            int i = 0;
            while (br.ready()) {
                String line = br.readLine();
                String array[] = line.split("@");
                for (int j = 0; j < adjMatrix.length; j++) {
                    adjMatrix[i][j] = Integer.parseInt(array[j]);
                }
                i++;
            }
        } catch (Exception e) {
            System.out.println("Error " + e);
        }
        return adjMatrix;
    }
}

Monday, May 14, 2012

Dijkstra Algorithm (Shortest Path Algorithm ) Java Code

Dijkstra Algorithm is used find the shortest path in a directed graphs. Following is a java implementation of the Dijkstra Algorithm.


class Dijkstra {

    public static void main(String[] args) {
        int length = 300;//length of the 2-D array
        int adjMatrix[][] = new int[length][length];
        CreateMatrix cm = new CreateMatrix();
        cm.createMatrix(length);
        adjMatrix = cm.readMatrix(adjMatrix);
        Dijkstra dk = new Dijkstra();
        dk.dijkstra(adjMatrix);

    }

    public void dijkstra(int adjMatrix[][]) {

        long startTime = System.nanoTime();
        int distance[] = new int[adjMatrix.length];
        int resolved[] = new int[adjMatrix.length];
        int prev[] = new int[adjMatrix.length];

        for (int i = 0; i < adjMatrix.length; i++) {
            distance[i] = Integer.MAX_VALUE;
            resolved[i] = Integer.MAX_VALUE;
            prev[i] = -1;
        }
        distance[ 0] = 0;
        resolved[ 0] = 0;

        int minNode = Integer.MAX_VALUE, position = 0;
        for (int i = 0; i < adjMatrix.length; i++) {
            for (int j = 0; j < resolved.length; j++) {
                if (minNode > distance[j] && resolved[j] != -1) {
                    minNode = distance[j];
                    position = j;
                }
            }
            resolved[position] = -1;

            for (int j = 0; j < adjMatrix.length; j++) {
                if (distance[j] > adjMatrix[position][j] + distance[position]) {
                    distance[j] = adjMatrix[position][j] + distance[position];
                    prev[j] = position;
                }
            }
            minNode = Integer.MAX_VALUE;
		}
        long runTime = System.nanoTime() - startTime;
        System.out.println("Runtime =" + runTime + " nano seconds");
        System.out.println("Distance Array");
        for (int j = 0; j < distance.length; j++) {
            System.out.print(" " + distance[j]);
        }
        System.out.println("");
        System.out.println("Predecessor Array");
        for (int i = 0; i < prev.length; i++) {
            System.out.print(" " + prev[i]);
        }
        System.out.println("");
    }
}

Friday, March 2, 2012

How to Resume Broken Downloads in Internet Download Manager

We all download movies music every day. Among all other download sites mediafire is the most famous hosting site. Internet Download Manager is the download accelerator most of the windows users are used to. So when we are downloading something using  a regular account what happens if a download is being interrupted. We have to download it from all the beginning. :(  So I'm going to explain a method to resume downloads and you don't have to  download from the beginning at all.  

This is the error you'll get when trying to resume a broken download...

Now right click on the download you want to resume and select properties. Then you'll probably get a screen as below.

Then copy the Address and paste it in a web browser. Then right click on the Copy the Link Location and copy the newly generated link..
Copy the Link Location
 Then in the Properties of the Download in the Internet Download Manager. Copy that link to the Address value.
Paste to address value

Now go to the Download list and select resume download.

Resume the Download
That's it. Now you'll see the download will resume.. :)

 Ok Now you can enjoy your downloading.... :)

Tuesday, February 14, 2012

UCSC Going Down 2012

I am very proud to say that I am a  member of the Batch 06 or the Batch 2007/2008 of UCSC. The things we did for our UCSC was unique and many would not implausible. (I would rather say as the best batch in the history of the UCSC and our seniors would agree with me too of course .. :) ) There were many occasions and functions we did, UCSC Going Down is the tribute to our seniors who have given the guidance to come along this journey. 
UCSC going down was held on 11th February 2012 on the UOC premises. Our guys and girls made a great contribution to make that event a success. So here are some of the photographs of that event and all the credits goes to our photographer Dulini or we all known as "Lenchiii".
Preparing the decorations
Guys working hard
Guess who is working huh.. ;)
from left Samitha, Supun, me and Chathura
Stage decorations
Some souvenirs
Drama event
Keshan in action
My apologies that I can't put all the pictures here and I would like to specially thank all the people who helped us in many ways to make this event a success.