Friday 6 December 2013

Creating a CON Folder in Windows

Create CON Folder in Windows 
Have you ever tried to create a CON folder or any folder with names such as “con”, “prn”, “nul” “com1″ “com2″ “lpt1″ etc. but failed? Is it impossible to create folders with such names in windows?
Well, the answer is NO and YES!
NO because, when create a new folder and try to rename it to any one of the above specified names, you know what happens! In Windows XP the folder name automatically changes back to “New Folder” no matter you try to renaming it any number of times. Where as in case of Windows Vista and Windows 7, when you try to rename the file you get an error message saying “The specified device name is invalid”.
What is the reason behind this? Simple, these names represent the internal devices of the operating system and hence we cannot create folders with the above names.
YES because it is still possible to create these folders using some simple methods as explained below:

1. Using the Command Prompt:

Here is a step-by-step procedure to create the “con” folder using the command prompt:
  1. Go to the command prompt:
  2. Type in the command prompt (For ex. To create a folder in the E: drive by name: “CON”)
    C:\>md \\.\e:\con
    NOTE: “con” can be replaced by any other names such as “prn”, “nul” “com1″ “com2″ “lpt1″ etc.
  3. In case if you wish to delete the folder, use the following command:
    C:\>rd \\.\e:\con
NOTE: This folder can only be deleted from the command prompt. You cannot remove it by right-click delete.

2. Using ALT Key and Numeric Keypad:

You can also use the Alt key and the Numeric keypad to accomplish the same job in a much easier way. Here is how you can do it:
  1. Create a New folder (Right-click -> New -> Folder)
  2. Once the new folder is created, right-click on it and select the option “Rename”.
  3. Hold down the ALT key and type 0160 from the numeric keypad (ALT+0160) and release the ALT key.
  4. Now, the folder name should go blank so that you can type any name of your choice such as “con”, “prn” “nul” etc. and press Enter. That’s it, you’re done!

C

C Program Without a Main Function

C Program without a main function 
Have you ever wondered how to write a C program without a main function? Can a C program execute with a main function? Is it possible to do that?
Well, the answer is YES! There can be a C program without a main function. Here is the source code of the program without a main function:
#include<stdio.h> #define decode(s,t,u,m,p,e,d) m##s##u##t #define begin decode(a,n,i,m,a,t,e) int begin() { printf(” hello “); }
The above program runs perfectly fine even without a main function. But how? What’s the logic behind it? How can we have a C program working without a main function. Read on to find out the answer…
Here, we are using a preprocessor directive called #define with arguments to give an impression that the program runs without the main function. However, in reality it runs with a hidden main function in it.
NOTE: A Preprocessor is program which processes the source code before compilation.
The ‘##‘ operator is called the token pasting or token merging operator. That is, we can merge two or more characters with it. Now, look at the 2nd line of program:
#define decode(s,t,u,m,p,e,d) m##s##u##t
What is the preprocessor doing here? The macro decode(s,t,u,m,p,e,d) is being expanded as “msut” (The ## operator merges m, s, u and t into msut). The logic is, when you pass (s,t,u,m,p,e,d) as argument it merges the 4th, 1st, 3rd and the 2nd characters (tokens).
Now, look at the third line of the program:
#define begin decode(a,n,i,m,a,t,e)
Here the preprocessor replaces the macro “begin” with the expansion decode(a,n,i,m,a,t,e). According to the macro definition in the previous line, the argument must be expanded so that the 4th, 1st, 3rd and the 2nd characters must be merged. In the argument (a,n,i,m,a,t,e) 4th, 1st, 3rd and the 2nd characters are ‘m’, ‘a’, ‘i’ and ‘n’.
So the third line “int begin” is replaced by “int main” by the preprocessor before the program is passed on to the compiler. That’s it.
The bottom line is that, there can never exist a C program without a main function. Here, we are just playing a gimmick that makes us believe that the program runs without the main, but there actually exists a hidden main function in the program. Here, we are using the proprocessor directive to intelligently replace the word “begin” by “main”. In simple words: int begin = int main.

Working of Antivirus Software

How antivirus works 
Due to ever increasing threat from virus and other malicious programs, almost every computer today comes with a pre-installed antivirus software on it. In fact, an antivirus has become one of the most essential software package for every computer.
Even though every one of us have an antivirus software installed on our computers, only a few really bother to understand how it actually works! Well, if you are one among those few who would really bother to understand how antivirus works, then this article is for you.

How Antivirus Works:

An antivirus software typically uses a variety of strategies in detecting and removing viruses, worms and other malware programs. The following are the two most widely employed identification methods:

1. Signature-based dectection (Dictionary approach)

This is the most commonly employed method which involves searching for known patterns of virus within a given file. Every antivirus software will have a dictionary of sample malware codes called signatures in its database. Whenever a file is examined, the antivirus refers to the dictionary of sample codes present within its database and compares the same with the current file. If the piece of code within the file matches with the one in its dictionary then it is flagged and proper action is taken immediately so as to stop the virus from further replicating. The antivirus may choose to repair the file, quarantine or delete it permanently based on its potential risk.
As new viruses and malwares are created and released every day, this method of detection cannot defend against new malwares unless their samples are collected and signatures are released by the antivirus software company. Some companies may also encourage the users to upload new viruses or variants so that, the virus can be analyzed and the signature can be added to the dictionary.
Signature based detection can be very effective, but requires frequent updates of the virus signature dictionary. Hence, the users must update their antivirus software on a regular basis so as to defend against new threats that are released daily.

2. Heuristic-based detection (Suspicious behaviour approach)

Heuristic-based detection involves identifying suspicious behaviour from any given program which might indicate a potential risk. This approach is used by some of the sophisticated antivirus software to identify new malware and variants of known malware.
Unlike the signature based approach, here the antivirus doesn’t attempt to identify known viruses, but instead monitors the behavior of all programs.
For example, malicious behaviours like a program trying to write data to an executable program is flagged and the user is alerted about this action. This method of detection gives an additional level of security from unidentified threats.
File emulation: This is another type of heuristic-based approach where a given program is executed in a virtual environment and the actions performed by it are logged. Based on the actions logged, the antivirus software can determine if the program is malicious or not and carry out necessary actions in order to clean the infection.
Most commercial antivirus software use a combination of both signature-based and heuristic-based approaches to combat malware.

Issues of Concern:

Zero-day threats: A zero-day (zero-hour ) threat or attack is where a malware tries to exploit computer application vulnerabilities that are yet unidentified by the antivirus software companies. These attacks are used to cause damage to the computer even before they are identified. Since patches are not yet released for these kind of new threats, they can easily manage to bypass the antivirus software and carry out malicious actions. However, most of the threats are identified after a day or two of its release, but damage caused by them before identification is quite inevitable.
Daily Updates: Since new viruses and threats are released every day, it is most essential to update the antivirus software so that the virus definitions are kept up-to-date. Most software will have an auto-update feature so that, the virus definitions are updated whenever the computer is connected to the Internet.
Effectiveness: Even though an antivirus software can catch almost every malware, it is still not 100% foolproof against all kinds of threats. As explained earlier, a zero-day threat can easily bypass the protective shield of the antivirus software. Also virus authors have tried to stay a step ahead by writing “oligomorphic“, “polymorphic” and, more recently, “metamorphic” virus codes, which will encrypt parts of themselves or otherwise modify themselves as a method of disguise, so as to not match virus signatures in the dictionary.
Thus user awareness is as important as antivirus software; users must be trained to practice safe surfing habits such as downloading files only from trusted websites and not blindly executing a program that is unknown or obtained from an untrusted source. I hope this article has helped you understand the working of an antivirus software.

Working of Domain Name System (DNS)

In the world of Internet and the area of computer networks, you will often come across the term Domain Name System or Domain Name Service which is simply referred to as DNS. The working of DNS forms one of the basic concepts of computer networks whose understanding is very much essential especially if you are planning to get into the field of ethical hacking or network security.
In this post, I will try to explain how Domain Name System works in a very simple and easy to follow manner so that even the readers who do not have any prior knowledge of computer networks should be able to understand the concept.

What is a Domain Name System?

A “Domain Name System” or “Domain Name Service” is a computer network protocol whose job is to map a user friendly domain name such as “Gohacking.com” to its corresponding IP address like “173.245.61.120″.
How Domain Name System (DNS) Works
Every computer on the Internet, be it a web server, home computer or any other network device has a unique IP address allotted to it. This IP address is used to establish connections between the server and the client in order to initiate the transfer of data. Whether you are trying to access a website or sending an email, the DNS plays a very important role here.
For example, when you type “www.google.com” on your browser’s address bar, your computer will make use of the DNS server to fetch the IP address of Google’s server that is “74.125.236.37″. After obtaining the IP address, your computer will then establish a connection with the server only after which you see the Google’s home page loading on your browser. The whole process is called DNS Resolution.
With millions of websites on the Internet, it is impossible for people to remember the IP address of every website in order to access it. Therefore, the concept of domain name was introduced so that every website can be identified by its unique name which makes it easy for people to remember. However, the IP address is still used as the base for internal communication by network devices. This is where the DNS comes in to action that works by resolving the user friendly domain name to its corresponding machine friendly IP address.
In simple words, domain names are for humans while IP addresses are for network devices. The “Domain Name System” is a protocol to establish a link between the two. Hence, it is not a surprise that you can even load a website by directly typing its IP address instead of the domain name in the browser’s address bar (give it a try)!

Types of DNS Servers and their Role:

The Domain Name System (DNS) is a distributed database that resides on multiple computers on the Internet in a hierarchical manner. They include the following types:

Root Name Servers:

The root servers represent the top level of the DNS hierarchy. These are the DNS servers that contain the complete database of domain names and their corresponding IP addresses. Currently, there are 13 root servers distributed globally which are named using the letters A,B,C and so on up to M.

Local Name Servers:

Local servers represent the most lower level DNS servers that are owned and maintained by many business organizations and Internet Service providers (ISPs). These local servers are able to resolve frequently used domain names into their corresponding IP addresses by caching the recent information. This cache is updated and refreshed on a regular basis.

How DNS Server Works?

Whenever you type a URL such as “http://www.gohacking.com” on your browser’s address bar, your computer will send a request to the local name server to resolve the domain name into its corresponding IP address. This request is often referred to as a DNS query. The local name server will receive the query to find out whether it contains the matching name and IP address in its database. If found, the corresponding IP address (response) is returned. If not, the query is automatically passed on to another server that is in the next higher level of DNS hierarchy. This process continues until the query reaches the server that contains the matching name and IP address. The IP address (response) then flows back the chain in the reverse order to your computer.
In rare cases where none of the lower level DNS servers contain the record for a given domain name, the DNS query eventually reaches one of the root name server to obtain the response.

FAQs about Domain Name System:

Here is a list of some of the FAQs about DNS:

How does a “root name server” obtain the information about new domains?

Whenever a new domain name is created or an existing one is updated, it is the responsibility of the domain registrar to publish the details and register it with the root name server. Only after this, the information can move down the DNS hierarchy and get updated on the lower level DNS servers.

What is DNS propagation?

Whenever a new domain name is registered or an existing one is updated, the information about the domain must get updated on all the major DNS servers so that the domain can be reached from all parts of the globe. This is called DNS propagation and the whole process can take anywhere from 24 to 72 hours to get completed.

How often the DNS servers are updated to refresh the cache?

There is no specific rule that defines the rate at which DNS servers should be updated. It usually depends on the organization such as the ISP that maintains the server. Most DNS servers are updated on an hourly basis while some may update their databases on a daily basis.
I hope you have now understood the working of DNS in a very convincing manner. Pass your comments and share your opinion.

Tips to Find Unauthorized Activity on Your Email Account

Find Unauthorized Activity on Your Email 
Do you suspect that your email account is under attack? Do you want to maintain the security of your email account and make it 100 percent hack proof? Well, Some times our email account might have got hacked and we may not be aware of that. We may believe that our email account is safe, but in reality our private and confidential information may be falling into the hands of a third person.
In this post, I will you will find information on how to find unauthorized activity on your email account if any and how to stop them.

Signs of Unauthorized Activity on an Email Account:

  1. Your new emails are marked as Read even if you’ve not read them.
  2. Your emails are moved to Trash or even permanently deleted without your notice.
  3. Your emails are being forwarded to a third party email address (check your settings-> forwarding).
  4. Your secondary email address or mobile number is changed.
If you come across any of the above activities on your email account, then it is a clear indication that your email account is hacked.

Additional Security Features in Gmail:

Gmail provides an additional security feature to protect your email account through the means of IP address logging. That is, Gmail records your IP address every time you log in to your Gmail account. So, if a third party gets access to your account then even his/her IP is also recorded. To see a list of recorded IP address, scroll down to the bottom of your Gmail account and you’ll see something like this.
Gmail - Last account activity
You can see from the above figure that Gmail shows the IP address of last login (last account activity). You can click on Details to see the IP address of your last 5 activities. If you find that the IP listed in the logs doesn’t belong to you, then there are chances of unauthorized activity.

Steps to Stop the Unauthorized Activity:

If you feel/suspect that your account is hacked, then you must immediately take the actions mentioned below:
    1. Change your Password
    2. Change your security question.
    3. Remove any third party email address (if any) to which your account is set to forward emails.
    4. Make sure that you can access the email account of your secondary email address.
    5. Also change your secondary email password and security question.
This ensures that your account is safe from future attacks. But I strongly recommend that you read my other post on How to protect your email account? I hope you liked this post. Please pass your comments. :)

Working of Email Spam Filters

How to Email Spam Filters Work 
If you are the one who works with emails on a daily basis, you are most likely to be using a SPAM FILTER to ease the job of sifting through a large number of spam emails every day.
Needless to say that spam filters do make our job a lot simpler by automatically filtering out the spam without which, it is almost impossible to manually filter the junk emails that arrive in millions each day. However, it is often necessary to have a basic knowledge of how spam filters actually work and on what basis they flag an email as spam.

How do Spam Filters Work?

There are different kinds of spam filters:

Header Spam Filters:

Header spam filters work by examining the header information of a particular email message to check if it appears to have been forged. The header of every email contains information which tells the origin of the email. ie: The incoming email ID and usually the IP address (server address) of the sender. So, spammers often forge the header to input a false sender ID and IP address so as to make it difficult to trace them.
Thus, if an email is supposed to have a forged header or if the same message is found to have been sent to multiple recipients, it is most likely considered as a spam by many filters. This method of spam filtering is often quite effective, however, occasionally it may result in some of the requested newsletters from being misdirected into the spam folders.

Content Spam Filters:

Content spam filter is one of the most effective and widely used filter to combat spam emails. They use a sophisticated algorithm with a set of pre-defined rules to determine whether a given email is a spam. They work by scanning the entire text/body of the email to search for specific words and patterns that make them resemble a typical spam message. Most content spam filters work based on the following criteria and check to see:
  1. If the message speaks a lot about money matter. Commonly suspected words include: lottery, discount, offer, bank account, money back guarantee etc.
  2. If the message contains adult terms like: viagra, pills, bed, drugs, hot and so on.
  3. If there is any sort of urgency. Most spam emails call for an urgency by using terms such as hurry, offer valid till etc.
  4. If the message contains a single large image with little or no text, it is often considered as spam by many filters.
Each content spam filter may have its own set of additional rules using which it evaluates each incoming email. In most cases, content and header spam filters are combined together to achieve higher level of accuracy.

Language Spam Filters:

Language spam filter is designed to simply filter out any email that is not in the user’s native language. Since spammers come from all parts of the world with different languages, a language spam filter can help get rid of those annoying emails that come in the languages that you cannot read!

User Defined Spam Filters:

User defined spam filters can be very handy, however they need a considerable amount of time investment in configuring and setting up a set the rules using which the filter works.
For example, the user can configure to have all the emails from friends and company to reach the inbox, newsletters to reach a secondary inbox and all those remaining to the spam folder. Here the user must carefully examine the patterns of spam emails that he receives from time to time and needs to set up the rules accordingly. This filter when improperly configured can sometime lead to false positives or false negatives.

Other Types of Spam Filters:

Popular webmail services like Gmail, Yahoo and Hotmail combine both header and content spam filtering techniques. In addition to this they also use their own algorithms to combat spam.
For example, services like Gmail uses “optical text recognition” to identify spammy text inside an image. Also, the users are provided with an option to “Report Spam” whenever a spam email accidentally reaches the inbox. With the user feedback, the filter learns and becomes more powerful in carrying out the filtering process.

Advantages of Using BCC While Sending an Email

Benefits of using BCC 
Almost every user on the Internet sends and receives hundreds of emails on a regular basis. However, only a handful of them know what is BCC and what are the advantages of using BCC while sending an email.
If you are one such Internet user who is unaware of what BCC is all about, then this is the post that you should definitely read!

What is BCC?

BCC stands Blind Carbon Copy. It refers to the practice of sending an email to multiple recipients without disclosing the individual emails addresses.
While sending the same email/message to multiple recipients, it is a common practice for most users to separate the email addresses by using comma or semi-colon and insert all those recipient addresses in the To: filed. When emails are sent in this way, each receiver is able to see the complete list of all the recipient email addresses to which the same message if being sent to.
Unlike the To: field, the BCC: option on the other hand allows you to hide the recipients in email messages. In other words, when emails are sent using BCC:,  the receiver will not be able to see the list of recipient email addresses. Thus, using BCC is a smart way to protect the privacy of the recipients.

Why should you use BCC?

Here are the reasons for using the BCC option:
Risk of Spammers: In order to avoid the risk of spammers, it is necessary that you encourage people/friends to use BCC: while forwarding any message to you. This prevents your email address from appearing in other person’s inbox thereby keeping yourself less exposed to spammers. 
While forwarding email messages, people often do not bother to remove the list of previous recipients.  As a result, messages that are repeatedly sent to many recipients may contain a long lists of email addresses. This makes it easy for the spammers to collect and target those email IDs for spamming.
Protect the Privacy: BCC provides an easy and simple option for protecting the privacy of your recipients. Under many circumstances it is necessary for us to send an email without letting the recipients know who else is receiving the same message. Also, it is highly recommended that you use the BCC: option while forwarding a joke or a funny email to a list of your friends. If you are sending email on behalf of a business or organization, it may be especially important to keep the list of clients, members, or associates confidential. So, don’t forget to use BCC: option in those instances wherever privacy matters.

How to BCC an email message?

Most email clients provide the BCC: option under a few lines below the To: field. All you have to do is just enter the list of recipients in the BCC: field instead of entering the same in the To: field. You may leave the To: field blank or enter your own email address. Once you do this, just hit the Send button.
The moral is that you should use BCC: while sending bulk messages so as to protect the privacy of your recipients.

How Firewalls Work

How Firewalls Work 
If you have been using Internet on a regular basis or working in a large company and surf the Internet while you are at work, you must have surely come across the term firewall.
You might have also heard of people saying “firewalls protect their computer from web attacks and hackers” or “a certain website has been blocked by firewall in their work place”. If you have ever wondered to know what exactly is this firewall and how it works, here we go. In this post I will try to explain “How firewalls work” in layman’s terms.

How Firewalls Work?

Firewalls are basically a barrier between your computer (or a network) and the Internet (outside world). A firewall can be simply compared to a security guard who stands at the entrance of your house and filters the visitors coming to your place. He may allow some visitors to enter while denying others whom he suspects of being intruders. Similarly a firewall is a software program or a hardware device that filters the information (packets) coming through the Internet to your personal computer or a computer network.
The working of a Firewall
Firewalls may decide to allow or block network traffic between devices based on the rules that are pre-configured or set by the firewall administrator. Most personal firewalls such as Windows firewall operate on a set of pre-configured rules that are most suitable under normal circumstances so that, the user need not worry much about configuring the firewall.
Personal firewalls are easy to install and use and hence preferred by end-users for use on their personal computers.  However, large networks and companies prefer those firewalls that have plenty of options to configure so as to meet their customized needs.
For example, a company may set up different firewall rules for FTP servers, Telnet servers and Web servers. In addition, the company can even control how the employees connect to the Internet by blocking access to certain websites or restricting the transfer of files to other networks. Thus, in addition to security, a firewall can give the company a tremendous control over how people use the network.
Firewalls use one or more of the following methods to control the incoming and outgoing traffic in a network:
  1. Packet Filtering: In this method, packets (small chunks of data) are analyzed against a set of filters. Packet filters has a set of rules that come with accept and deny actions which are pre-configured or can be configured manually by the firewall administrator. If the packet manages to make it through these filters then it is allowed to reach the destination; otherwise it is discarded.
  2. Stateful Inspection: This is a newer method that doesn’t analyze the contents of the packets. Instead, it compares certain key aspects of each packet to a database of trusted source. Both incoming and outgoing packets are compared against this database and if the comparison yields a reasonable match, then the packets are allowed to travel further. Otherwise they are discarded.

Firewall Configuration:

Firewalls can be configured by adding one or more filters based on several conditions as mentioned below:
    1. IP addresses: In any case, if an IP address outside the network is said to be unfavorable, then it is possible to set  filter to block all the traffic to and from that IP address. For example, if a certain IP address is found to be making too many connections to a server, the administrator may decide to block traffic from this IP using the firewall.
    2. Domain names: Since it is difficult to remember the IP addresses, it is an easier and smarter way to configure the firewalls by adding filters based on domain names. By setting up a domain filter, a company may decide to block all access to certain domain names, or may provide access only to a list of selected domain names.
    3. Ports/Protocols: Every service running on a server is made available to the Internet using numbered ports, one for each service. In simple words, ports can be compared to virtual doors of the server through which services are made available.
      For example, if a server is running a Web (HTTP) service then it will be typically available on port 80. In order to avail this service, the client needs to connect to the server via port 80. Similarly, different services such as Telnet (Port 23), FTP (port 21) and SMTP (port 25) services may be running on the server.
      If the services are intended for the public, they are usually kept open. Otherwise they are blocked using the firewall so as to prevent intruders from using the open ports for making unauthorized connections.
    4. Specific words or phrases: A firewall can be configured to filter one or more specific words or phrases so that, both the incoming and outgoing packets are scanned for the words in the filter.
      For example, you may set up a firewall rule to filter any packet that contains an offensive term or a phrase that you may decide to block from entering or leaving your network.

Hardware vs. Software Firewall:

Hardware firewalls provide higher level of security and hence preferred for servers where security has the top most priority. The software firewalls on the other hand are less expensive and hence preferred in home computers and laptops.
Hardware firewalls usually come as an in-built unit of a router and provide maximum security as it filters each packet in the hardware level itself even before it manages to enter your computer. A good example is the Linksys Cable/DSL router.

Why Firewall?

Firewalls provide security over a number of online threats such as Remote login, Trojan backdoors, Session hijacking, DOS & DDOS attacks, viruses, cookie stealing and many more. The effectiveness of the security depends on the way you configure the firewall and how you set up the filter rules.
However, major threats such as DOS and DDOS attacks may sometimes manage to bypass the firewalls and do the damage to the server. Even though firewall is not a complete answer to online threats, it can most effectively handle the attacks and provide security to the computer up to the maximum possible extent.

 

Net Sim

All resources of ns 
http://hpds.ee.ncku.edu.tw/~smallko/ns2/ 
 
How to measure the throughput, packet drop rate, and end-to-end delay for UDP-based application over wireless networks ?

[scenario]
        It consists of 8 mobile nodes: 4 source nodes and 4 destination node. Each source is a CBR source over UDP. The size of a transmitted packet is 512 bytes. Transmission rate of a node is 600 Kbps. We assumed that the nodes are in transmission range at a constant distance of 195 m. The simulation time lasted for 80 sec.

[TCL script] source from Joe Naoum-Sawaya
# ====================================================================
# Define Node Configuration paramaters
#====================================================================
set val(chan)           Channel/WirelessChannel    ;# channel type
set val(prop)           Propagation/TwoRayGround   ;# radio-propagation model
set val(netif)           Phy/WirelessPhy            ;# network interface type

set val(mac)            Mac/802_11                ;# MAC type
set val(ifq)            Queue/DropTail/PriQueue   ;# interface queue type

set val(ll)             LL                         ;# link layer type
set val(ant)            Antenna/OmniAntenna        ;# antenna model
set val(ifqlen)         50                         ;# max packet in ifq
set val(nn)             8                          ;# number of mobilenodes
set val(rp)             DSDV                       ;# routing protocol
set val(x)              500                        ;# X dimension of the topography
set val(y)              500                           ;# Y dimension of the topography

Mac/802_11 set RTSThreshold_  3000
Mac/802_11 set basicRate_ 1Mb
Mac/802_11 set dataRate_  2Mb

#=====================================================================
# Initialize trace file desctiptors
#=====================================================================
# *** Throughput Trace ***
set f0 [open out02.tr w]
set f1 [open out12.tr w]
set f2 [open out22.tr w]
set f3 [open out32.tr w]

# *** Packet Loss Trace ***
set f4 [open lost02.tr w]
set f5 [open lost12.tr w]
set f6 [open lost22.tr w]
set f7 [open lost32.tr w]

# *** Packet Delay Trace ***
set f8 [open delay02.tr w]
set f9 [open delay12.tr w]
set f10 [open delay22.tr w]
set f11 [open delay32.tr w]

# *** Initialize Simulator ***
set ns_              [new Simulator]

# *** Initialize Trace file ***
set tracefd     [open trace2.tr w]
$ns_ trace-all $tracefd

# *** Initialize Network Animator ***
set namtrace [open sim12.nam w]
$ns_ namtrace-all-wireless $namtrace $val(x) $val(y)

# *** set up topography object ***
set topo       [new Topography]
$topo load_flatgrid 500 500

# Create  General Operations Director (GOD) object. It is used to store global information about the state of the environment, network, or nodes that an
# omniscent observer would have, but that should not be made known to any participant in the simulation.

create-god $val(nn)

# configure nodes
        $ns_ node-config -adhocRouting $val(rp) \
                         -llType $val(ll) \
                         -macType $val(mac) \
                         -ifqType $val(ifq) \
                         -ifqLen $val(ifqlen) \
                         -antType $val(ant) \
                         -propType $val(prop) \
                         -phyType $val(netif) \
                         -channelType $val(chan) \
                         -topoInstance $topo \
                         -agentTrace ON \
                         -routerTrace ON \
                         -macTrace OFF \
                         -movementTrace OFF                   

# Create Nodes

        for {set i 0} {$i < $val(nn) } {incr i} {
                set node_($i) [$ns_ node]
                $node_($i) random-motion 0            ;# disable random motion
        }

# Initialize Node Coordinates

$node_(0) set X_ 5.0
$node_(0) set Y_ 5.0
$node_(0) set Z_ 0.0

$node_(1) set X_ 200.0
$node_(1) set Y_ 5.0
$node_(1) set Z_ 0.0

$node_(2) set X_ 5.0
$node_(2) set Y_ 50.0
$node_(2) set Z_ 0.0

$node_(3) set X_ 200.0
$node_(3) set Y_ 50.0
$node_(3) set Z_ 0.0

$node_(4) set X_ 5.0
$node_(4) set Y_ 100.0
$node_(4) set Z_ 0.0

$node_(5) set X_ 200.0
$node_(5) set Y_ 100.0
$node_(5) set Z_ 0.0

$node_(6) set X_ 2.0
$node_(6) set Y_ 150.0
$node_(6) set Z_ 0.0

$node_(7) set X_ 200.0
$node_(7) set Y_ 150.0
$node_(7) set Z_ 0.0

# Setup traffic flow between nodes
# UDP connections between node_(0) and node_(1)

# Create Constant four Bit Rate Traffic sources

set agent1 [new Agent/UDP]             ;# Create UDP Agent
$agent1 set prio_ 0                   ;# Set Its priority to 0
set sink [new Agent/LossMonitor]  ;# Create Loss Monitor Sink in order to be able to trace the number obytes received
$ns_ attach-agent $node_(0) $agent1     ;# Attach Agent to source node
$ns_ attach-agent $node_(1) $sink ;# Attach Agent to sink node
$ns_ connect $agent1 $sink            ;# Connect the nodes
set app1 [new Application/Traffic/CBR]  ;# Create Constant Bit Rate application
$app1 set packetSize_ 512               ;# Set Packet Size to 512 bytes
$app1 set rate_ 600Kb                    ;# Set CBR rate to 200 Kbits/sec
$app1 attach-agent $agent1             ;# Attach Application to agent

set agent2 [new Agent/UDP]             ;# Create UDP Agent
$agent2 set prio_ 1                   ;# Set Its priority to 1
set sink2 [new Agent/LossMonitor]         ;# Create Loss Monitor Sink in order to be able to trace the number obytes received
$ns_ attach-agent $node_(2) $agent2     ;# Attach Agent to source node
$ns_ attach-agent $node_(3) $sink2        ;# Attach Agent to sink node
$ns_ connect $agent2 $sink2                  ;# Connect the nodes
set app2 [new Application/Traffic/CBR]  ;# Create Constant Bit Rate application
$app2 set packetSize_ 512               ;# Set Packet Size to 512 bytes
$app2 set rate_ 600Kb                    ;# Set CBR rate to 200 Kbits/sec
$app2 attach-agent $agent2             ;# Attach Application to agent

set agent3 [new Agent/UDP]             ;# Create UDP Agent
$agent3 set prio_ 2                   ;# Set Its priority to 2
set sink3 [new Agent/LossMonitor]         ;# Create Loss Monitor Sink in order to be able to trace the number obytes received
$ns_ attach-agent $node_(4) $agent3     ;# Attach Agent to source node
$ns_ attach-agent $node_(5) $sink3        ;# Attach Agent to sink node
$ns_ connect $agent3 $sink3                  ;# Connect the nodes
set app3 [new Application/Traffic/CBR]  ;# Create Constant Bit Rate application
$app3 set packetSize_ 512               ;# Set Packet Size to 512 bytes
$app3 set rate_ 600Kb                    ;# Set CBR rate to 200 Kbits/sec
$app3 attach-agent $agent3             ;# Attach Application to agent

set agent4 [new Agent/UDP]             ;# Create UDP Agent
$agent4 set prio_ 3                   ;# Set Its priority to 3
set sink4 [new Agent/LossMonitor]         ;# Create Loss Monitor Sink in order to be able to trace the number obytes received
$ns_ attach-agent $node_(6) $agent4     ;# Attach Agent to source node
$ns_ attach-agent $node_(7) $sink4        ;# Attach Agent to sink node
$ns_ connect $agent4 $sink4                  ;# Connect the nodes
set app4 [new Application/Traffic/CBR]  ;# Create Constant Bit Rate application
$app4 set packetSize_ 512               ;# Set Packet Size to 512 bytes
$app4 set rate_ 600Kb                    ;# Set CBR rate to 200 Kbits/sec
$app4 attach-agent $agent4             ;# Attach Application to agent

# defines the node size in Network Animator

for {set i 0} {$i < $val(nn)} {incr i} {
    $ns_ initial_node_pos $node_($i) 20
}

# Initialize Flags
set holdtime 0
set holdseq 0

set holdtime1 0
set holdseq1 0

set holdtime2 0
set holdseq2 0

set holdtime3 0
set holdseq3 0

set holdrate1 0
set holdrate2 0
set holdrate3 0
set holdrate4 0

# Function To record Statistcis (Bit Rate, Delay, Drop)

proc record {} {
        global sink sink2 sink3 sink4 f0 f1 f2 f3 f4 f5 f6 f7 holdtime holdseq holdtime1 holdseq1 holdtime2 holdseq2 holdtime3 holdseq3 f8 f9 f10 f11 holdrate1 holdrate2 holdrate3 holdrate4
       
        set ns [Simulator instance]
       
    set time 0.9 ;#Set Sampling Time to 0.9 Sec

        set bw0 [$sink set bytes_]
        set bw1 [$sink2 set bytes_]
        set bw2 [$sink3 set bytes_]
        set bw3 [$sink4 set bytes_]

        set bw4 [$sink set nlost_]
        set bw5 [$sink2 set nlost_]
        set bw6 [$sink3 set nlost_]
        set bw7 [$sink4 set nlost_]

        set bw8 [$sink set lastPktTime_]
        set bw9 [$sink set npkts_]

        set bw10 [$sink2 set lastPktTime_]
        set bw11 [$sink2 set npkts_]

        set bw12 [$sink3 set lastPktTime_]
        set bw13 [$sink3 set npkts_]

        set bw14 [$sink4 set lastPktTime_]
        set bw15 [$sink4 set npkts_]
       
    set now [$ns now]
       
        # Record Bit Rate in Trace Files
        puts $f0 "$now [expr (($bw0+$holdrate1)*8)/(2*$time*1000000)]"
        puts $f1 "$now [expr (($bw1+$holdrate2)*8)/(2*$time*1000000)]"
        puts $f2 "$now [expr (($bw2+$holdrate3)*8)/(2*$time*1000000)]"
        puts $f3 "$now [expr (($bw3+$holdrate4)*8)/(2*$time*1000000)]"

        # Record Packet Loss Rate in File
        puts $f4 "$now [expr $bw4/$time]"
        puts $f5 "$now [expr $bw5/$time]"
        puts $f6 "$now [expr $bw6/$time]"
        puts $f7 "$now [expr $bw7/$time]"

        # Record Packet Delay in File
        if { $bw9 > $holdseq } {
                puts $f8 "$now [expr ($bw8 - $holdtime)/($bw9 - $holdseq)]"
        } else {
                puts $f8 "$now [expr ($bw9 - $holdseq)]"
        }

        if { $bw11 > $holdseq1 } {
                puts $f9 "$now [expr ($bw10 - $holdtime1)/($bw11 - $holdseq1)]"
        } else {
                puts $f9 "$now [expr ($bw11 - $holdseq1)]"
        }

        if { $bw13 > $holdseq2 } {
                puts $f10 "$now [expr ($bw12 - $holdtime2)/($bw13 - $holdseq2)]"
        } else {
                puts $f10 "$now [expr ($bw13 - $holdseq2)]"
        }

        if { $bw15 > $holdseq3 } {
                puts $f11 "$now [expr ($bw14 - $holdtime3)/($bw15 - $holdseq3)]"
        } else {
                puts $f11 "$now [expr ($bw15 - $holdseq3)]"
        }
       
        # Reset Variables
        $sink set bytes_ 0
        $sink2 set bytes_ 0
        $sink3 set bytes_ 0
        $sink4 set bytes_ 0

        $sink set nlost_ 0
        $sink2 set nlost_ 0
        $sink3 set nlost_ 0
        $sink4 set nlost_ 0

        set holdtime $bw8
        set holdseq $bw9

        set  holdrate1 $bw0
        set  holdrate2 $bw1
        set  holdrate3 $bw2
        set  holdrate4 $bw3

    $ns at [expr $now+$time] "record"   ;# Schedule Record after $time interval sec
}


# Start Recording at Time 0
$ns_ at 0.0 "record"

$ns_ at 1.4 "$app1 start"                 ;# Start transmission at time t = 1.4 Sec

$ns_ at 10.0 "$app2 start"               ;# Start transmission at time t = 10 Sec

$ns_ at 20.0 "$app3 start"               ;# Start transmission at time t = 20 Sec

$ns_ at 30.0 "$app4 start"               ;# Start transmission at time t = 30 Sec

# Stop Simulation at Time 80 sec
$ns_ at 80.0 "stop"

# Reset Nodes at time 80 sec

for {set i 0} {$i < $val(nn) } {incr i} {
    $ns_ at 80.0 "$node_($i) reset";
}

# Exit Simulatoion at Time 80.01 sec
$ns_ at 80.01 "puts \"NS EXITING...\" ; $ns_ halt"

proc stop {} {
        global ns_ tracefd f0 f1 f2 f3 f4 f5 f6 f7 f8 f9 f10 f11

        # Close Trace Files
        close $f0 
        close $f1
        close $f2
        close $f3

        close $f4 
        close $f5
        close $f6
        close $f7

        close $f8
        close $f9
        close $f10
        close $f11

        # Plot Recorded Statistics
        exec xgraph out02.tr out12.tr out22.tr out32.tr -geometry 800x400 &
        exec xgraph lost02.tr lost12.tr lost22.tr lost32.tr -geometry 800x400 &
        exec xgraph delay02.tr delay12.tr delay22.tr delay32.tr -geometry 800x400 &
       
        # Reset Trace File
        $ns_ flush-trace
        close $tracefd
       
        exit 0
}

puts "Starting Simulation..."
$ns_ run


[simulation results]

Throughput:
Analysis: Node 1 starts transmitting at time T =1.4 sec while Node 2 starts transmitting at time T=10 sec. During the period of time [1.4 sec, 10 sec] Node 1 is the only transmitting node using the entire available bandwidth. This justifies the high performance of Node 1 during the specified interval of time. At time T=10 sec, Node 2 starts transmission hence sharing channel resources with Node 1. This explains the heavy reduction of bit rate. In addition, the bit rate plot experiences heavier oscillations and reduction as the number of transmitting nodes increases. Oscillations are reflected in heavy disorders in network performance.

Packet Drop Rate:
Analysis: This figure shows a high packet drop rate whenever the number of nodes sharing network resources increases. It can be shown that the packet drop rate in the interval [1.4 sec, 10 sec] is 0. This can be easily justified since only one node is using the network during this time interval. However this high-quality performance is deteriorated as more nodes start sharing the network resources.

Average Packets End to End Delay:
Analysis: When the number of nodes that are sharing the network resources, the delay significantly increases and readjusting CW of each node takes longer time.

[Reference]
J. Naoum-Sawaya, B. Ghaddar, S. Khawam, H. Safa, H. Artail, and Z. Dawy, "Adaptive Approach for QoS Support in IEEE 802.11e Wireless LAN," in  IEEE International Conference on Wireless and Mobile Computing , Networking and Communications (WiMob 2005), Montreal, Canada, August 2005