Wednesday, November 18, 2009

Core Java interview questions with Code Example

Question: How could Java classes direct program messages to the system console, but error messages, say to a file?

Answer: The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This how the standard output could be re-directed:


import java.io.*;

public class HelloWorld {
public static void main(String[] args) {
try {
PrintStream st = new PrintStream(new FileOutputStream("test.txt"));
System.setOut(st);
System.setErr(st);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}


Question: Explain the usage of the keyword transient?

Answer: Serilization is the process of making the object's state persistent. That means the state of the object is converted into stream of bytes and stored in a file. In the same way we can use the de-serilization concept to bring back the object's state from bytes. Sometimes serialization is necessary. For example, when we transmit objects through network, we want them to be consistent, therefore these objects have to be sterilizable,

On the other hand, we don't want the value of some member variable to be sterilizable, for instance, the password, then we use the keyword transient. When the class will be de-serialized, the transient variable will be initialized to 0 or null.


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Logon implements Serializable {
private transient String password;

public Logon(String pwd) {
password = pwd;
}

public String toString() {
return password;
}

public static void main(String[] args) throws Exception {
Logon a = new Logon("hello_world");
System.out.println("logon a = " + a);
ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream(
"Logon.out"));
o.writeObject(a);
o.close();
Thread.sleep(1000); // Delay for 1 second
// Now get them back:
ObjectInputStream in = new ObjectInputStream(new FileInputStream(
"Logon.out"));
System.out.println("Recovering object at after 1 second");
a = (Logon) in.readObject();
System.out.println("logon a = " + a);
}
}


The output of the above example will be:

logon a = hello_world
Recovering object at after 1 second
logon a = null

Tuesday, November 17, 2009

Linux Commands - Hardware

* uname - print the OS information. "uname -a" display kernel-name, nodename, kernel-release, kernel version, machine, processor, hardware-platform, and operating system.
* dmesg - print comprehensive kernel and driver messages. For example, "dmesg >> file_to_mail_out.txt" output the information to a file for future trouble-shooting.
* top - display the system resources usage, and the updating processes.
* free - check memory usage.
* swapon - manage swap file or partition. "swapon -s" displays a summary of the swap usage.
* vmstat - display virtue memory information.
* lsof - list all the open files, sockets and pipes.
* tty - print the file name of the terminal connected to standard input.

* fdisk - manage disk partition. "fdisk -l" displays partition table.
* cfdisk - a easier progrom based on fdisk.
* fdformat - low-level format a floppy disk.

* eject - eject removable media.
* mount - unix file system is arranged in one big tree. mount attaches the file system found in some device into the big tree. "mount /dev/cdrom" mount the iso9660 file system found on the CDROM.
* unmount - unix file system is arranged in one big tree. unmount detaches the file system found in some device from the big tree. "unmount ./isoimage" unmount the iso9660 file system found on the file isoimage.

* import - "import screenshots" take a screen shots from x-window, save it to a file screenshots.

* ifconfig - displays the network interfaces.
* ifup - "ifup eth1" brings up a network interface eth1.
* ifdown - brings down a network interface.

* lpr - "lpr file.txt" sent the file.txt to default printer.
* lprm - remove the current printing job.
* pr - preformat a file for printing. "pr | lpr file.txt"

Monday, November 16, 2009

Linux Commands - Programming

* cksum - calculate the check sum of a file, used to verify if two files are identical. Example: "cksum file1.txt" returns a number as the finger print of the file1.txt.

* echo - "echo $PATH" displays the value of environment variable PATH.
* env - displays all environment variable.
* export - write a variable to harddis. Example: "export MYVAR=$HOME" assigns the value of HOME to MYVAR, then set MYVAR as an environment variable.
* declare - declare variables and give them attributes. Example: "declare MYVAR=$HOME" assigns the value of HOME TO MYVAR, but does NOT set MYVAR as environment variable.
* read - read input from standard input, assign it to a variable. Example: "read newvar", input a value for newval, then "echo $newvar".
* sleep - delay for a some time. Example: "sleep 2" delay 2 seconds.

* alias - allow users to create abbreviations for complex commands. Example: "alias" displays all the existing aliases. Example: "alias mycmd="pwd" "
* unalias - delete an alias. Example: "unalias mycmd".
* nohup - run a command immune to hungups. Example: "nohup ls" run the command ls, write the output to file nohup.out.
* tee - "ls | tee file.out" this command display the output of command ls at standard output, while write them to the file.out. "ls >> file.out" won't display the output at standard output.
* sed - search and replace patterns in a file. Example: sed 's/my/your/g' afile.txt --this command substitute all "my" to "your" in the afile.txt.
* cut - divide a file into several parts. Example: "cut -d, -f1,3 sample.txt" divide lines by delimiter :, then output the first and third columns.
* sort - sort text files.
* paste - merge lines of files.
* split - split a file into many parts. Example: "split -b 1024 example.data new" split example.data into file newaa, newab, newac... each file have 1024 byte.
* vi - text editor.

* top - display the system resources statistics, and the updating processes.
* ps - display the running processes. "ps -A" displays all the running processes.
* kill - stop a process from running. "kill -9 3214" stops the process with id 3214 immediately.

* watch - execute a program periodically. Example: "watch -n 5 free" execute command free every 5 second.
* crontab - schedule tasks running periodically. Example: "crontab -l" list all the scheduled tasks for the current user. "crontab -e" edit the scheduler. For example, a task record could be "2 12 * * 5 /sbin/ping -c 1 www.google.com >> /dev/null", which means, ping google every 2 minutes at 12 o'clock on every friday. "crontab -d" delete all the scheduled tasks for the current user.

* chkconfig - control services. "chkconfig" displays the states of all the system services. "chkconfig sshd on" turn on the ssh service.

Linux Commands - network

* vncpasswd - create a passwd for the vnc server.
* vncserver - create x-window display so that vncclient can remote login. Example: "vncserver :10 -geometry 1280x960" create a display :10 with size 1280x960. "vncserver -kill :10" stops the display :10.
* ftp - connect to a ftp server and is useful to manage your webpage hosting site. Example."ftp youracount.x10hosting.com".
* telnet - remote login to a host, not secure, use ssh instead.
* ssh - open an ssh session on a remote host. Example: "ssh guy@192.168.1.100" will login host 192.168.1.100 with user guy.
* scp - copy files from/to remote host using ssh. Example: "scp guy@192.168.1.100:test.txt /some/local/directory/" will copy file test.txt from site 192.168.1.100 to local machine.
* wget - Retrieve web pages or files via HTTP, HTTPS or FTP. Example: "wget http://www.google.com/index.html" will download the webpage index.html from google site.

* netstat - powerful network debug tool. Example: "netstat" displays all sockets. "netstat -r" displays routing table. "netstat -s" displays summary of protocols.
* ping - ping a remote host. Example: "ping -c 3 www.google.com" send 3 ping packets to google.
* traceroute - trace the route to a remote host. Example "traceroute www.google.com" will find all the router hops to google.
* iptables - administration tool for IPv4 packets filtering and NAT. Exmple: "iptables -l" list all rules for all chains.

* write - send message to a user loging into the machine. Example: "send guy" will open a sending box to pass a message to user guy. Control + D to close the message window.
* mail - send smtp mail. You should have a MTA such as postfix installed on your host in order to send mail. Example: "echo This will go into the body of the mail. | mail -s “Hello world” you@youremailid.com".

* hostname - display or set the host name for local machine.
* host - simple dns loop up. Example: "host www.google.com" get the ip address of google. "host 204.228.150.3" reverse loop up the domain for ip address.
* dig - detailed dns look up. Example: "dig kl2217.x10hosting.com" shows the A, CNAME, NS records of the dns loopup. "dig kl2217.x10hosting.com MX" shows the mail server loopup records.
* nslookup - interactive dns look up tool.

Linux Commands - system administration

* su - log into root account.
* df - quick check for the disk space. "df -h -T" -h let output human readable, -T shows the file system type.
* du - quick check for file size. "du -h" shows the size of folders and files under current directory in a more readable format.
* finger - check who is on the system. fingure followed by user id shows detail history of a user.
* passwd - change the passwd of the current user. type in passwd then enter, you will be asked for old password then new password.
* dd - disk duplicate. "dd if=/dev/hdb1 of=/backup/", if stands for input file, of stands for output file.
* shutdown - shutdown the system. -h flag means halt, -r indicates reboot. For example "shutdown -h +120" will put the system into hibernate after 120 min.
* tar - zip and unzip files or directory. "tar cvfz tarball.tar.gz ./directory/" archive and compress the directory "dir" into file "tarball.tar.gz", "tar xvf tarball.tar.gz" unzip it. c means create new, x means untar, v means berbose, f means file.
* chmod - change file permission. "chmod 777 filename" give read, write, execute permission to owner, group and world. 7 = 4 + 2 + 1 = r + w + x.
* chown - change file's owner. "chown me file1" change file1's owner to "me".
* chgrp - change file's group. "chown users file1" changes file1's group to "users".
* id - print user and group id.
* groups - view the groups a user belongs to. "groups root" display all the groups root belongs to.
* groupadd - create new group. "groupadd mygroup" create a new group mygroup.
* groupmod - modify a group. "groupmod -n testgroup mygroup" change the name of mygroup to testgroup.
* groupdel - delete a group. "groupdel testgroup" delete the group testgroup.
* useradd - add a user. "useradd -g mygroup myuser" add the user myuser to group mygroup.
* usermod - modify a user. "usermod -g users myuser" change the group of myuser to users.
* userdel - delete a user. "userdel myuser" delete the user myuser.

Linux Commands - basic commands

* ls - files in the current directory.
* cd - working directory. If your current path is /home/username/Trash for instance, typing "cd" will bring you back to /home/username.
* mkdir - a new directory
* rmdir - a directory (must be empty)
* touch - "touch filename" create a new file "filename".
* cp - such as "cp currentFile newFile", and is used to copy files.
* diff - compares two files, "diff file1 file2" compares each line of file1 and file2, displays the difference.
* mv - such as "mv currentLocation newLocation". This is used to either move or rename files.
* rm - such as "rm myFile"; it is used to delete files permanently. "rm -r existingdir" will remove the existing directory named 'existingdir' and all directories and files below it.
* ln - create a shortcut. For example "ln -s orignial symlink" create a symbolic file "symlink" pointing to the file "original"
* pwd - the working (current) directory.
* cat - files (can be used to join them together), and prints its output to standard output (the terminal screen). Used like: "cat myFile".
* less - for file viewing in the shell, and is most useful for text files; invoked like "less myFile".
* tail - show the last 10 lines of a file, and is very useful to view a updating file. For example: "tail -f /var/log/messages" shows the last 10 lines of changing log file messages.
* whereis - show where the binary, source and manual page files are for a command. For example "whereis ifconfig".
* find - be used to find files via the command line. Example usage could be: "find . -name toc", which looks at the current directory (defined by ".") for any files with the name "toc".
* grep - be used to find lines contains a specific pattern. For example : "grep root /etc/passwd" find all lines contains string "root" in the file passwd.
* date - the current date! This can also be used to set the date of the system (but administrator privileges are required).For example: # date -s "2 OCT 2006 18:00:00"
* history - in shell command for the BASH environment that shows the last run commands.

Saturday, October 17, 2009

Find a Hacker suspicious

I captured suspicious upnp traffic on my computer with wireshark. A Linux hacker is turning my computer into a network service provider for him. This is the general description about upnp.

http://www.upnp-hacks.org/upnp.html

This hacker is located in China, GuangDong. The hacker software is installed by a online flash game client. To remove the threat, I blocked the port used by the upnp.

Wednesday, October 7, 2009

MAC vs. PC vs. Linux

It's a never ending war betwen MAC, PC and Linux.
It is started with "Get A MAC" campaign:



PC quickly faught back on the youtube with "MAC Spoof" episode:
Mac Spoof: Security [Low Quality]

Mac Spoof: Upgrading [Low Quality]

Mac Spoof: Services [Low Quality]

The voice from Linux soon was heard in video "Novell Get a MAC Spoof".







I like to watch these videos, because they are funny, but I won't let them influence my judgement. I personally use windows, mac os and linux, and love them all.

Let's face it, windows has been so deeply rooted on the market, you can not just flip your fingers and let it go. window is easy to use and softwares just work on it.

I like MAC too. MAC has cool interface, mac os 10 have a Linux in the core, did I mention how fast it boots up?

So, why linux? Because it is free forever! Your hardware don't work? ok, let's write a driver. You want a specific service? ok, let's load the module. Under the name of Linux, nothing is impossible, because everything is up to you. You are free.

Thursday, July 30, 2009

Why wireless network is insecure and how to secure it

This video is a general introduction to wireless security.
To improve your wireless security.
  • Out of the box WiFi is generally insecure.
  • Enable wireless encryption via WPA.
  • Change the default router password.
  • Change the default wireless SSID.
  • Hide the SSID.
  • Secure all home workstations.

Saturday, July 25, 2009

My bad experience on fedora 10 network bug


One of my friends chat with me on msn, saying that she just installed a new linux system, but the firefox connects nowhere, so she was in panic. After finding out their office didn't use dhcp, I realized what she wants is to set static ip address and default gateway. Simple enough.
I wish I knew fedora 10 have a network bug for static ip configuration, but I didn't!
I went through the normal steps.
Check OS information with "uname -a" and "dmesg head -1".
Check network information with "ifconfig", "/sbin/route -n" and a few ping and traceroute.
Ask my friend for the default gateway and the previous ip address (it's better to use the previous ip to save us from nasty kinks).
Educate my friend about the Linux desktop, where to find the GUI to fill in the ip address and default gateway.
Ahaaaa, here's the catch! She kept complaining that linux automatically changes netmask to gateway...
So, I decided to go the sure way --
Ask her to add default gateway into
/etc/sysconfig/network
/etc/sysconfig/network-scripts/ifcfg-eth0
And restart the network service by typing "service network restart"

She still complained that linux automatically changes netmask to gateway...

I got confused, but make another try -- "route add default gw xxx.xxx.xxx.xxx eth0" -- and got more confused after getting "siocaddrt no such process".

Now it's my time to panic...
After googling for a while, this post finally explained everything:
"Unfortunately, to date (8th/Dec/2008) there is a bug with system-config-network (GUI Version) in which it incorrectly stores the network mask as the default gateway address."
"Fedora 10 disables the "network" service in preference to using "NetworkManager", therefore NetworkManager will need to be disabled before enabling and configuring the network service."

Now I'm happy my friend's firefox can link to pages.

[ Socialize This]

Wednesday, July 15, 2009

STAR WARS Episode you never seen before



To watch the move.
In windowsXP,
press "START"
press "Run..."
type "command" then ENTER
type "telnet" then ENTER
type "O" then ENTER
type "towel.blinkenlights.nl" then ENTER

Just wait and enjoy the brand new STAR WARS Episode...

[ Socialize This]

Tuesday, July 14, 2009

How to setup VPN Server at home

If you have a PC with windows XP professional and a router supporting port-forward, then you can setup a VPN server at home without cost a penny.
Even PPTP based VPN is criticized for low security compared with L2TP/IPSec based VPN, Microsoft Inc. is constantly promoting it. The PPTP VPN client is included by default in all versions of windows XP, windows vista. If you have windows XP Professional, you can even set up a PPTP based VPN server at home. The good side is PPTP based VPN setup don’t cost you a penny, and functioned the same as those expensive cisco gateway backed VPN setup; the bad side is, you should be aware of the security issue facing the PPTP VPN — for PPTP the authentication process is not done over secured connections hence credentials can be lost to hackers and thus they can have access to the VPN server. The secure connection is setup only after the authentication is done.
To set up VPN, you should do three things.
Task #1: Having a router supporting port-forward. (Here is a farely completed list for routers supporting port-forward. My recommandation is LINKSYS WRT54GL. It is a perfect router for someone with networking experience who wants an inexpensive router to do expensive networking tasks.)
Task #2: Configure your router so that the traffic at your router’s port TCP-1723 will be forwarded to the local IP address of the PC running your VPN server software.
Port Forwarding How to
Task #3: Enable and configure the VPN server software at that home PC.
Simple PPTP VPN Server Setup in Windows XP
Now, the VPN client on the internet can access your VPN network anywhere, the only thing the client need to know is your router’s external IP address (which is dynamically assigned by your ISP) and the password of your VPN (of course). The IP address may change now and then, so your VPN client need to adjust the IP address accordingly.
If updating the dynamic IP address annoys you, you can ask a software to do this for you.
This is how to: firstly bind the dynamic IP address to a domain name, then point your VPN client to the domain name, so that no update is needed at the client side. At the server side, a software periodically tests your external IP address, then binds the new IP address to the domain name. no-ip.com have already wrote such a software for you, they even provide free domain name! If you are a hard-core programmer and dare not trust the softwares downloaded from the web, writing a software in Java or C++ is not that hard.

[ Socialize This]

Monday, July 13, 2009

Yahoo! 360° is closing today

Finally, the rumor became reality, the Yahoo! 360° is closing today. Here is the official declaration from yahoo! site:
"Make sure to save or download your existing content before July 13, 2009. On this date, all remaining material on Yahoo! 360° will no longer be accessible."

Yahoo! 360° has many nice blog feature to it, easy to use and give user a social networking site running by Yahoo!. As many users noticed long time ago, Yahoo! 360° gets slower and slower, besides, the social aspect of Yahoo! 360° turned out not so successful, there are plenty of other social networking sites which just fulfill a different function.

I think many users will move to blogger or blogspot after the closing.

[ Socialize This]

Monday, July 6, 2009

How to remote contorl your LAN computers


If you have followed my previous posts on how to set up workgroup and file sharing in your home network.

You maybe commuted between your computers to configure, debug, inspect results... What a hack...

How nice if we can sit on one computer and remote control other computers without physically walked there. Fortunetly, we have a very easy solution with VNC server.

"VNC is remote control software which allows you to view and fully interact with one computer desktop (the "VNC server") using a simple program (the "VNC viewer") on another computer desktop anywhere on the Internet. The two computers don't even have to be the same type, so for example you can use VNC to view a Windows Vista desktop at the office on a Linux or Mac computer at home. For ultimate simplicity, there is even a Java viewer, so that any desktop can be controlled remotely from within a browser without having to install software."
To set up VNC server-client connections.
Download and install RealVNC (Free Edition is good enough) from

SelectVNC Free Edition for Windows
Installer including both Server and Viewer
Follow the install wizard, which will show you how to configure a vnc server on your computer so that other computers can remote control your computer after login with password. The wizard also installs a vnc viewer, so that you can remote login and control other vnc-server installed computers.

After installing vnc servers and clients on all your home computers.

Sit in front of one of your pc, Click START -> All Programs -> RealVNC -> VNC viewer 4 -> Run VNC viewer
In the server text box, type in the IP address of the remote computer and click OK. In the next screen, input the correct password and click OK.

Walla, magic.

Enable File-sharing in windows xp

In my previous post, I have set up a workgroup on windows xp computers. In this post, I will go through a few steps to enable the simple file sharing.

Step 1, enable simple file sharing.
For winxp pro:
Double click My Computer -> Tools -> Folder Options -> View -> make sure "User simple file sharing [Recommended]" is checked.

Step 2, modify shared documents properties.
For winxp Home Edition:
Double Click My Computer -> Right Click Shared Documents -> Click Sharing tab -> Check "Share this folder on the network" and "Allow network users to change my files".
For winxp Professional:
Double Click My Computer -> Double Click Shared Documents -> Right Click the folders you want to share and change the Sharing properties one by one.

Now go to START -> My Network Places -> Viw workgroup computers -> Double Click the computer in your workgroup, the shared folder shows up. You can copy/paste or drag/drop files from/to that remote folder.

Windows workgroup debug "User has not been Granted the Requested Login Type"

In my previous post, I demonstrated how to set up windows workgroup.

Setting up windows workgroup is easy, only if you are lucky enough.
The most common error message ppl bumped into is:

"\\xxx is not accessible. You might not have permission to use this network resource. Contact the administrator of this Server to find out if you have access permissions."

A lot of reason can cause the above error message.

1. Check the firewall settings (it may even prevent you to ping through).
Go to START -> Control Panel -> Securety Center -> Windows Firewall -> Select OFF
and see if the error gets fixed. If so, you may turn on firewall and change the firewall exceptions.

2. Make sure user "Guest" is enabled.
Go to START -> Control panel -> User Accounts -> click User Accounts -> Make sure Guest is turned on.

3. For windows xp pro, you may need to modify the Local Security Policy to allow the Guest to access the computer from network.
Go to START -> Control Panel -> Performance and Maintainance -> Administrative Tools -> Local Security Policy -> Local Policy -> User Rights Accessment
Find the key "Deny access to this computer from network", double click the key, high-light "Guest", Click remove, Click OK.

4. In some odd situations, you may need to check the registry to make sure restrictanonymous key is correctly set.

Click Start, click Run, type regedit, and then click OK.
Locate and then double-click the following registry subkey:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa
On the right side, double-click restrictanonymous.
Make sure that the value in the Value data box is set to 0, and then click OK.
Close Registry Editor.
Restart the computer.

5. If none of the above works, here is the ultimate solution from John Will.
Download the Windows Server 2003 Resource Kit Tools from microsoft Download center, which are a set of tools to help administrators streamline management tasks.

After installation is complete, click on: Start -> All Programs -> Windows Resource Kit
Tools -> Command Shell

Then enter the following commands. (Attention: they are case sensitive.)

net user guest /active:yes
ntrights +r SeNetworkLogonRight -u Guest
ntrights -r SeDenyNetworkLogonRight -u Guest
The first command enables network access for Guest, the two subsequent ones change two different policies to allow network access for Guest.

So far, the errors should be clean and you should be able to double click into the computers on your local workgroup. However, nothing too interesting there except the default folder "Printers and Faxes". To enable file-sharing, we need to do a few tweeks, which will be discussed in my next post.

[ Socialize This]

How to set up windows home network


If you have more than 2 computers in your home, you may want to connect them together so that you can share files and resources among them.

There are two types of windows network you can set up -- domains and workgroup.

Windows domain is basically a server/client system, which is more secure and feature rich. How ever, you need a computer installed with Windows 2000 Server or Windows 2003 server as the dedicated domain server.

Comparably, setting up the peer to peer workgroup network is much easier on all versions of windows operation system, of course, it is not as secure.


To set up a workgroup in windows xp:
  • Right click on the My Computer icon and choose PROPERTIES from the menu.

  • Select the COMPUTER NAME tab

  • Select the CHANGE button

  • In the Workgroup text box, type a workgroup name of your choice and click OK. This workgroup name must be the SAME for all the computers in your Home Network. In the Computer name text box, type a unque name for this computer.

  • Now Click OK.

  • Click OK at the bottom of this window. When prompt for restart computer, Click OK.

  • Repeat the above process for all the computers in your home, remember the workgroup name must be the SAME!
Now your workgroup-based home network have been setup. You can find your workgroup peers by clicking START -> My Network Places -> View Workgroup Computers.
If you click on the other computer in the Network it may only show you the SHARED FOLDERS that Windows sets up by default. To view other computers Folders and Files you must now share those items.

Better chances are you got error message such as "You might not have permission to use this network resource". Don't panic, we all got error messages. check my next post on how to trouble-shooting this.


Sunday, July 5, 2009

Wordpress blog came back

I sent a message to the supporting team to explain the problem, now it's back.

Thursday, July 2, 2009

Blog on WordPress got suspended

WordPress.com

This blog has been archived or suspended for a violation of our Terms of Service.


The above scaring image is what I saw when visiting my blog at wordpress tonight.

I wonder what happened to my blog?

As I google "This blog has been archived or suspended for a violation of our Terms of Service. wordpress". I realized many people got automatically banned by their Spam-Filter. Wordpress's current Spam-Filter technology using words or links alone to detect the untrustworthy content, which isn’t context-aware. They may ban ppl for a bad link in the post or ban ppl because of taking others content.

I guess a post copied from a blog caused the trouble, but I I DO put a link to the source at the first line of my post as source article! Anyway, I should receive an email from their supporting group soon.

By the way, complaining on the WordPress.com Forums is not an option now, because the supporting group became clever after dealing with numerous similar cases.

You've been blocked. If you think a mistake has been made, contact this site's administrator.

Back to WordPress.com Forums.

[ Socialize This]

Wednesday, July 1, 2009

How to implement network protocol

network stack
network stack


Common questions regarding the network protocols include:
What is network protocol?
Why network protocol?
How to implement network protocol?

The best way to answer the question of "What" and "Why" is looking into a helloworld-style example of network protocols -- Time Protocol. Then the question "How" will follow naturally.

Here it is: the Time Protocol, defined in RFC 868.
Network Working Group J. Postel - ISI
Request for Comments: 868 K. Harrenstien - SRI
May 1983

Time Protocol
This RFC specifies a standard for the ARPA Internet community. Hosts on
the ARPA Internet that choose to implement a Time Protocol are expected
to adopt and implement this standard.
This protocol provides a site-independent, machine readable date and
time. The Time service sends back to the originating source the time in
seconds since midnight on January first 1900.
One motivation arises from the fact that not all systems have a
date/time clock, and all are subject to occasional human or machine
error. The use of time-servers makes it possible to quickly confirm or
correct a system's idea of the time, by making a brief poll of several
independent sites on the network.
This protocol may be used either above the Transmission Control Protocol
(TCP) or above the User Datagram Protocol (UDP).

When used via TCP the time service works as follows:
S: Listen on port 37 (45 octal).
U: Connect to port 37.
S: Send the time as a 32 bit binary number.
U: Receive the time.
U: Close the connection.
S: Close the connection.

The server listens for a connection on port 37. When the connection
is established, the server returns a 32-bit time value and closes the
connection. If the server is unable to determine the time at its
site, it should either refuse the connection or close it without
sending anything.
Postel [Page 1]
RFC 868 May 1983
Time Protocol
When used via UDP the time service works as follows:
S: Listen on port 37 (45 octal).
U: Send an empty datagram to port 37.
S: Receive the empty datagram.
S: Send a datagram containing the time as a 32 bit binary number.
U: Receive the time datagram.

The server listens for a datagram on port 37. When a datagram
arrives, the server returns a datagram containing the 32-bit time
value. If the server is unable to determine the time at its site, it
should discard the arriving datagram and make no reply.
The Time
The time is the number of seconds since 00:00 (midnight) 1 January 1900
GMT, such that the time 1 is 12:00:01 am on 1 January 1900 GMT; this
base will serve until the year 2036.
For example:
the time 2,208,988,800 corresponds to 00:00 1 Jan 1970 GMT,
2,398,291,200 corresponds to 00:00 1 Jan 1976 GMT,
2,524,521,600 corresponds to 00:00 1 Jan 1980 GMT,
2,629,584,000 corresponds to 00:00 1 May 1983 GMT,
and -1,297,728,000 corresponds to 00:00 17 Nov 1858 GMT.

After reading through the 2 page definition document, which is self-explaining, we can see
A protocol is a set of rules used by computers to communicate with each other across a network. In the case of Time Protocol, it defines the way Server and User communicate about the time and the syntax of the time.

At this point, we are eager to materialize the protocol with the Time server and the Time client. But wait, questions:

Question #1: What is the time format to use?
Let's check RFC 868 -- Aha, "The time is the number of seconds since 00:00 (midnight) 1 January 1900GMT, such that the time 1 is 12:00:01 am on 1 January 1900 GMT; thisbase will serve until the year 2036." Clear enough.

Question #2: Where to start?
Let's check the RFC 868 again:
"This protocol may be used either above the Transmission Control Protocol(TCP) or above the User Datagram Protocol (UDP)."

Ok, now we know, we can build our server-client on top of TCP or UDP service (usually provided by code libraries). Sure enough, Java/C/Python/Perl... all have socket library which allow an application to connect to ports on remote host, listen to local port, send data, receive data, close connection, etc. So, very doable!

Question #3: How to synchronize the server and client?
Let's check the RFC 868 again (and again):
When used via TCP the time service works as follows:
S: Listen on port 37 (45 octal).
U: Connect to port 37.
S: Send the time as a 32 bit binary number.
U: Receive the time.
U: Close the connection.
S: Close the connection.
The server listens for a connection on port 37. When the connection
is established, the server returns a 32-bit time value and closes the
connection. If the server is unable to determine the time at its
site, it should either refuse the connection or close it without
sending anything.
That's almost the pseudo code!

Before we jump right into the code, notice protocols may be implemented by hardware, software, or a combination of the two. When implemented in software, the programming language doesn't matter. As long as the implementation follow the protocol defined in RFC xxx, it shall work, that's why we need network protocols!

Implementaion in Python

time_client.py
# File:time_client.py
import socket
import struct, time
# server
HOST = "www.python.org"
PORT = 37
# reference time (in seconds since 1900-01-01 00:00:00)
TIME1970 = 2208988800L # 1970-01-01 00:00:00
# connect to server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
# read 4 bytes, and convert to time value
t = s.recv(4)
t = struct.unpack("!I", t)[0]
t = int(t - TIME1970)
s.close()
# print results
print "server time is", time.ctime(t)
print "local clock is", int(time.time()) - t, "seconds off"
time_server.py
# File:time_server.py
import socket
import struct, time
# user-accessible port
PORT = 8037
# reference time
TIME1970 = 2208988800L
# establish server
service = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
service.bind(("", PORT))
service.listen(1)
print "listening on port", PORT
while 1:
# serve forever
channel, info = service.accept()
print "connection from", info
t = int(time.time()) + TIME1970
t = struct.pack("!I", t)
channel.send(t) # send timestamp
channel.close() # disconnect

Learn Network Basics With Interesting Video

The interesting movie follows the life journey of a network packet in the net.


His journey starts from the web browser, where he was born at a click then met his fellow citizens ICMP ping packets, ping of death packets, TCP packets, UDP packets, AppleTalk packets... He went out from the LAN, entered into the WAN, reached his destination LAN and finally found the web server he is looking for. During the journey, he met a lot of vivid characters such as web browser, proxy server, router, firewall, router switch, internet backbone,webserver...
[ Socialize This]

Friday, June 26, 2009

How to redirect gmail




You can redirect the emails sent to your gmail account to other email address.
Step 1
On the upper-right corner of your gmail webpage, Select
Settings -> Forwarding and POP/IMAP

Step 2
In the "Forwarding:" tab
click the radio button in front of "Forward a copy of incoming mail to"

Step 3
In the textbox "email address", change "email address" to the email address you want to foward to.

Step 4
Press save changes.

What is Spam2.0

I bumped into a new jargon "Spam2.0" or "Spam 2.0" recently.

After some research, I found out the word "Spam2.0" or "Spam 2.0" is originated from a post on Official Google WebMaster Center Blog by Jason Morrison, a member of Search Quality Team today. There is no google product called "Spam2.0" or "Spam 2.0" so far. The author seems to refer to spam targeting Web2.0 websites as "Spam2.0" or "Spam 2.0".

original post.

[ Socialize This]

Thursday, June 25, 2009

Whois databases

The main whois database for the top-level domains ".com", ".net", and ".org" can be searched through any of the following sites:
The InterNIC Whois Search *
Domain registrars -- each with their own whois database
BetterWhois.com
AllWhois.com
SWITCH Whois Gateway
Google - Domain Name Search
Yahoo Whois Directory
The following Whois databases can be searched for information on other areas of the Internet, including Asian, Caribbean, European, and Latin American countries, and the ".mil" and ".gov" domains:
American Registry for Internet Numbers Whois
Asia Pacific IP Address Allocations Whois
European IP Address Allocations Whois
Latin American and Caribbean Internet Addresses Registry
US Military Whois - requires authorization to access
US Government Whois
Matt Power's Whois Servers List provides a long list of searchable world wide whois database servers.

[ Socialize This]

What is spam hunting

A favorite sport among many people is spammer hunting. It begins when you receive a piece of spam in the mail. Instead of deleting it, spam hunters track down who sent it, and take action, usually resulting in a loss of account for the spammer.

To find out the spam source, check out the Whois database.

If the address is hosted at a legitimate provider such as yahoo, google, they usually have a team to address violation of their terms of usage such as spamming, and you can fill the response forms at their web site to report the problem. They will often close the account.

If the address is part of a larger site like a community home page site, then you can complain to that site's administrators -- they will often close the user's account.


[ Socialize This]

How do spammers get email addresses?

Be aware that vicious spammers can collect the spam list in various ways, the best way to protect yourself from spam is not to give out the email address publicly.

Spammer can generally get your email address in the following ways:


From Spambot harvest
Spambots is a software like scrawl and spider, which basically follow links and grab email addresses from "mailto" links. Spambots can scour usernet/newsgroups/webpage/blogs and grab email addresses from post body and newsreader settings.

From a mailing list
Spammers join a mailing list, then gather the email addresses of the members, either from a list of the members provided by the mailing list software, or from people as they post.

From email reply
The spammer can got your email address from mail-servers using dictionary attacks then send you a email requesting for a reply. The email can be anything from "if you are interested please reply" or "if you want to be removed from the mailing list, please reply". If you replied, the spammer's email address was verified as valid by your email-server then the spammer can sent you more spam in the future.

From other spammers
Some spammers harvest the email address then sell it to other spammers using "Over 1 million email addresses on a CD"

[ Socialize This]

What is dictionary attack

Dictionary attack is an old cracker's trick aiming for vulnerable e-mail servers such as Hotmail and MSN servers. The cracker utilizes software that opens a connection to the mail server and then automatically submits random e-mail addresses. Many of these addresses are similar, such as "JONATHANjm8q631rj7ROSENBLATT@hotmail.com" and "JONATHANjm8q631rj8ROSENBLATT@hotmail.com." The software then records which addresses are "live" and adds the addresses to the spammer's list. Many mail server nowadays protected against dictinary attack.

[ Socialize This]

Spammer alert "Leve LED unique jewellery atelier"

A company claimed "Leve LED unique jewellery atelier" sent out a lot of emails through multiple hotmail accounts asking the user to submit resume to level.dep@gmail.com or leveldep@gmail.com ...

This company seems to be a spammer, they maybe use software to register many slightly different accounts from Hotmail and MSN servers, then use those hotmail accounts to spread the spam and collect personal informations in a few gmail accounts. Google have disabled the gmail accounts mentioned above, but those hotmail accounts are still at large. Learn how spammer get your email address and spam hunting.
The spam email looks like the following:

“Hello!

My name is Beata Hellmyrs and I am representative of Leve LED unique jewellery atelier. Our atelier is looking for a responsible and dedicated person on the position of purchasing agent.

The main responsibility is to deal with individual orders of our customers.

Salary: USD 3000 per month.

Timing: free schedule, part-time.

Requirements: good employment history (not necessarily in procurement field), ability to meet the deadlines and good analytical skills.

Employment: contract-base position for a foreign company (Our atelier is located in Sweden, Stockholm)

Training and supervisory during starting period are provided.

More information about the position you'll be able to learn during phone interview.

If you are interested in our job proposal, please send us your resume leveldep@gmail.com and we will contact you.

Thank you!”

[ Socialize This]

Monday, June 22, 2009

binary, decimal, and hex numbers

There are three major number systems in network, binary, decimal and hex numbers.
The binary numeral system, or base-2 number system represents numeric values using two symbols, usually 0 and 1.
The decimal number system, or base-10 number system represents numeric values using 10 symbols, 0,1,2,3,4,5,6,7,8,9, which we use everyday.
The hex number system, or base-16 number system represents numeric values using 16 symbols, 0,1,2,...8,9, a, b, c, d, e, f.

For example, a subnet mask 255.255.255.224, can be expressed in binary as 11111111.11111111.11111111.11100000, in decimal as 255.255.255.224 or in hex as ff.ff.ff.e0.

In cyber world, binary and hex reign, owing to their straightforward implementation in digital electronic circuitry using logic gates. Binary and hex are actually much simpler than decimal, if we can cast away our prejudice for these "strangers".

Since both binary and hex are machine friendly, it is very simple to convert between them.
16 = 2^4, so it takes four digits of binary to represent one digit of hexadecimal.

Binary to Hex convert
Given a binary number 11100000, we divide it into 4 digits groups as 1110,0000, then convert each group to its hex counter part, d for 1110 (1111 is f, so 1110 is f minus 1 -- d) and 0 for 0000, thus the answer e0.

Hex to Binary convert
The same applied to hex-binary convert. Given hex number f0, we divide it into two groups as f,0, then convert each group to its binary counter part, f for 1111, 0 for 0000, thus the answer 11110000.

Convert from hex and binary to decimal or vise versa is a little bit harder, because there's no natural relationship between them. (By the way, Arab mathematician Abu'l-Hasan al-Uqlidisi invented the decimal number system. If he picked 16 instead of 10 as the base number from the beginning, he would have saved us zillions of headach!!)

A decimal number 224 have value:
224 = 2*base^2 + 2*base^1 + 4*base^0 = 2*100 + 2*10 + 4, the same rule applied to binary and hex.
Binary to Decimal convert
Given binary number 11100000, we begin from the most significent bit (leftmost), the first 1 is at the eighth bit, thus represents value 1*base^(8-1) = 1*2^7 = 128. The second 1 is at the seventh bit, thus represents value 1*base^(7-1) = 2^6 = 64, the third one 2^5 = 32, the first 0 represents 0*2^4 = 0... Finally the value is 128+64+32+0+0+0....+0 = 224.

Hex to Decimal convert
Given hex number e0, we begin from the most significent bit (leftmost), the first e is at the second bit, thus represents value e*base^(2-1) = 14*16^1 = 224. The second 0 is at the first bit, thus represents value 0*base^(1-1) = 0*16^0 = 0. Finally the value is 224+0 = 224.

Decimal to Binary convert
Short division by two with remainder, it relies only on division by two.
Given decimal number 224, write the decimal number as the dividend inside an upside-down "long division" symbol. Write the base of the destination system (in our case, "2" for binary) as the divisor outside the curve of the division symbol.
2)224
_______

Write the integer answer (quotient) under the long division symbol, and write the remainder (0 or 1) to the right of the dividend.
2)224 0
_______
112
Continue downwards, dividing each new quotient by two and writing the remainders to the right of each dividend. Stop when the quotient is 1.
2)224 0
_______
2)112 0
_______
2 )56 0
_______
2 )28 0
_______
2 )14 0
_______
2 ) 7 1
_______
2 ) 3 1
_______
2) 1 1
_______
2) 0 0
_______

Starting with the bottom 1, read the sequence of 1's and 0's upwards to the top. You should have 11100000. This is the binary equivalent of the decimal number 224.

Hex to Binary convert
Short division by 16 with remainder, it relies only on division by 16.
Given decimal number 224, write the decimal number as the dividend inside an upside-down "long division" symbol. Write the base of the destination system (in our case, "16" for hex) as the divisor outside the curve of the division symbol.
16)224
_______
Write the integer answer (quotient) under the long division symbol, and write the remainder (0 to f) to the right of the dividend.
16)224 0
_______
14
Continue downwards, dividing each new quotient by 16 and writing the remainders to the right of each dividend. Stop when the quotient is less than 16.
16)224 0
_______
16) 14 e
_______
Starting with the bottom, read the sequence of digits upwards to the top. You should have e0. This is the hex equivalent of the decimal number 224.

[ Socialize This]

Friday, June 19, 2009

Apple released a new iPhone today




Apple Inc. release a new iPhone today. It’s now selling the 8-gigabyte version of the year-old iPhone 3G for $99, half the original price. Analysits predicts a 500,000 sell this weekend. At this moment, the apple stock is 138.50, rose 2.6 percent in Nasdaq Stock Market trading.


In the background of economy downturn and the recent recovery signs, apple's strategy seems to using massive production to compensate the 50% price cut and gaining more market share from its rivals like Palm and RIM. As the the recession easing at the third quarter and consummers spend more, apple together with AT&T could expand its bussiness easily riding the trend of another economy upturn. Just think about the potential market -- moving most of the desk top applications onto the smart phone and re-invent your living room by integrating your TV, home studio, video game, social network, internet, etc. into one smart system.



Wednesday, June 17, 2009

Cisco's 3 Layered Model

Over years of building network equipment, Cisco Systems has developed a three Layered model. Starting with the basics, the Cisco network is traditionally defined as a three-tier hierarchical model comprising the core, distribution, and access layers. Cisco both developed their system according to this model and recommend their end-users to follow the same philosophy.

History
The cisco three layered model is originated from the enterprise campus network which has evolved over the last 20 years.

Early LAN-based computer networks were made of small number of simply connected servers, PCs and printers. The first generation of campus networks came into form by interconnecting these LANs. Problems in one area of the network ofter impacted the entire network and a failure in one part of the campus often affected the entire campus network.

To address the above problems, Cisco borrowed the structured programming design principle from software engineer. Based on two complementary principles: hierarchy and modularity, large complex Cisco system must be built using a set of modularized components that can be assembled in a hierarchical and structured manner. The hierarchy is Cisco's three Layered Model.

Discription of Cisco Layers

Core Layer
The core layer is literally the internet backbone, the simplest yet most critical layer. The primary purpose of the core is to provide fault isolation and backbone connectivity, in another words, the core must be highly reliable and switch traffic as fast as possible. Therefore, on one hand, the core must provide the appropriate level of redundancy to allow fault tolerance in case of hardware/software failure or upgrade; on the other hand, the high-end switches and high-speed cables are implemented to achieve High data transfer rate and Low latency period.

The core means to be simple and provides a very limited set of services. We shouldn't implement complex policy services or attach user/server connections directly at this layer.

Examples of core layer Cisco equipment include:
Cisco switches such as 7000, 7200, 7500, and 12000 (for WAN use)
Catalyst switches such as 6000, 5000, and 4000 (for LAN use)
T-1 and E-1 lines, Frame relay connections, ATM networks, Switched Multimegabit Data Service (SMDS)

Distribution Layer
The distribution layer acts as an interface between the access layer and the core layer. The primary function of the distribution layer is to provide routing, filtering, and WAN access and to determine how packets can access the core, if needed.

While core layer and access layer are special purpose layers, the distribution layer on the other hand serves multiple purposes. It is an aggregation point for all of the access layer switches and also participates in the core routing design. This layer includes LAN-based routers and OSI layer 3 switches. It ensures that packets are properly routed between subnets and VLANs.

Access Layer
The access layer is sometimes referred to as the desktop layer. The network resources the workgroup and users needed will be available locally.

The access layer is the edge of the entire network, where wide variety of types of consumer devices such as PCs, printers, cameras attach to the wired portion of the network, various services provided, and dynamic configuration mechanisms implemeted. As a result, the access layer is most feature-rich layer of the Cisco three layered model.

List 1 lists examples of the types of services and capabilities that need to be defined and supported in the access layer of the network.

Enable MAC address filtering: It is possible to program a switch to allow only certain systems to access the connected LANs.
Create separate collision domains: A switch can create separate collision domains for each connected node to improve performance.
Share bandwidth: You can allow the same network connection to handle all data.
Handle switch bandwidth: You can move data from one network to another to perform load balancing.

^up
[ Socialize This]

TCP/IP Layered Model




The TCP/IP model was created by the U.S. Department of Defencse (DoD), to create a network that could survive any conditions. Some of the layers in the TCP/IP model have the same names as layers in the OSI model. TCP/IP is a "protocal specific" model while OSI model is "protocal independent" model.

Application Layer: Include the OSI Application, Presentation and Session Layer.

Transport Layer: Similar to OSI, with transmission control protocol (TCP) and user datagram protocal (UDP) operating at this layer.

Internet Layer: Similar to OSI Network layer. IP resides at this layer.

Network Access Layer: Combines all functionality of physical and Data Link layers of OSI model.

Normally, application programmers are concerned only with interfaces in the Application Layer and often also in the Transport Layer, while the layers below are services provided by the TCP/IP stack in the operating system. Microcontroller firmware in the network adapter typically handles Network Access issues, supported by driver software in the operational system. Non-programmable analog and digital electronics are normally in charge of the physical components in the Network Access Layer, typically using an ASIC chipset for each network interface or other physical standard.

What's a browser



[ Socialize This]

Bing continue to gain market share

Microsoft Corp.'s new Bing search engine was available two weeks ago, with a $100 million marketing campain.

Just in two weeks, Microsoft's share of search results pages -- a measure of the intensity of search activity by online users -- rose to 12.1% between June 8 and June 12.

It is unclear, if bing will shake the dominate position of Google and Yahoo which have U.S. market share around 60% and 20% respectively.

Compared with Google, bing has a more attractive user interface, and optimized for searching on shopping, travel, health and local businesses. Rumors said, Larry Page had teamed up his top experts to analyze the bing's algorithms. The war is coming? Let's see.

[ Socialize This]

Obama Sees 10% Unemployment Rate


June 17 -- In an interview of the President yesterday by Hunt, Obama predicted the jobless rate will continue to climb from its current 25-year high of 9.4 percent as employers are slow to take on new workers.



Hunt: Will unemployment reach 10%?
President: “Yes,”
Hunt: Before the end of this year?
President: “Yes,”
President: “I think that what you’ve seen is that the pace of job loss has slowed and I think that the economy is going to turn around. But as you know, jobs are a lagging indicator. And we've got to produce 150,000 jobs every month just to keep pace. we will end up seeing recovery shortly.”


Biggest Health Care Reform in US history is coming


June 17 (Bloomberg) -- The largest expansion of U.S. health care since the creation of Medicare in 1965 may emerge from legislation designed to reshape the medical industry and change how Americans receive and pay for care.

Congress today begins crafting legislation that Democratic leaders plan to push through both chambers by their August recess. The measure may require all Americans to get medical insurance, force insurers to accept all patients and end the tax break for employer-paid health benefits. These changes may be hammered out with unprecedented speed at the urging of President Barack Obama, who four days ago said “this is the moment.” The U.S. will spend more than $2 trillion this year on health care, the Health and Human Services department reported in February.

Obama has made a health-care overhaul his top domestic priority, using his February budget proposal to call it a “moral” imperative to extend coverage to the country’s 46 million uninsured. Obama also tied the long-term fiscal soundness of the U.S. to controlling medical costs. Health care consumes 18 percent of the U.S. economy and may rise to 34 percent by 2040, the White House Council of Economic Advisers reported June 2. The coming weeks will be pivotal if the House and Senate are to meet their goal to send Obama a single bill in October. “The president wants a bill by Oct. 15,” Baucus said in an interview yesterday. “He’ll get it.”

One issue is taxing employer-provided health benefits, which Obama opposed during his presidential campaign. In an interview yesterday with Bloomberg News, Obama said he wouldn’t rule out such a proposal.

“I don’t want to predetermine the best way to do this,” he said. “I’ve already put forward what I think is the best way. Let me see what comes out of the Hill and we’ll have that debate then.”

[ Socialize This]

Tuesday, June 16, 2009

ISO's OSI Layered Model - Summary

network stack
network stack

The picture is the summary of the 7 OSI layer we have discussed before.

ISO's OSI Layered Model - Application Layer


The application layer provides the services that directly support an application running on a host. This layer is closest to the end user. Examples of layer 7 services include:
FTP, Telnet, HTTP, DHCP, DNS, Gopher, SNMP, NIS, NNTP, SIP, SSI, NFS, NTP, SMPP, SMTP, RIP, BGP, etc.

previous [page 9] next

[ Socialize This]

ISO's OSI Layered Model - Presentation Layer


This layer provides independence from differences in data representation (e.g., encryption) by translating from application to network format, and vice versa. The presentation layer works to transform data into the form that the application layer can accept. This layer formats and encrypts data to be sent across a network, providing freedom from compatibility problems. It is sometimes called the syntax layer.

Most file format belong to this layer, such as QuickTime, TIFF, JPEG, TDI, ASCII, EBCDIC, MIDI, MPEG, etc.

previous [page 8] next

[ Socialize This]

ISO's OSI Layered Model - Session Layer


The Session Layer controls the dialogues (connections) between computers. It establishes, manages and terminates the connections between the local and remote application.
Synchronization of communicating applications comes into play,
The Session Layer is commonly implemented explicitly in application environments that use remote procedure (RPC) calls. RPC may be built on either TCP or UDP. Login sessions uses TCP whereas NFS and broadcast use UDP.

The session layer examples include SQL, RPC, XWindows, etc.

previous [page 7] next

[ Socialize This]

ISO's OSI Layered Model - Application Set





We have walked through the first 4 layers of OSI model.
Layer 1, physical layer.
Layer 2, DataLink Layer.
Layer 3, Network Layer.
Layer 4, Transport Layer.

which is low-level infrastructure of network, and can be grouped as transport set. In the next 3 articles, we will introduce the layers in the application set, which is closer to the end user and more software application stuff--
Layer 5, Session Layer.
Layer 6, Presentation Layer.
Layer 7, Application Layer.

previous [page 6] next

ISO's OSI Layered Model - Transport Layer





The OSI Model layer 4 is Transport Layer. This layer maintains flow control of data and provides for error checking and recovery of data between the source and the destination. Transport Layer messages are called segments or transport protocal data units (TPDUs). Unlike the hop-by-hop communication at network layer, transport layer is an end-to-end communication -- that is -- the two communicating hosts need not be concerned with the topology of the internet work, which lies between them. They only need to know the state of their communication.

Two transport protocols, Transmission Control Protocol (TCP) and User Datagram Protocol (UDP), sits at the transport layer.


TCP establishes connections between two hosts on the network through 'sockets' which are determined by the IP address and port number. The sender of data, first establishes a logical connection with the prospective receiver of the data, sends the data and then terminates the connection. TCP is connection oriented and uses a 3 way handshake to establish a connection before data is sent.

UDP on the other hand provides a low overhead transmission service, but with less error checking. The sender does not establish a contact with the receiver first. Whenever there is a data packet ready to be sent, it independently routes the packet to a gateway. UDP is a connectionless protocal at the transport layer.

The device at transport layer is gateway. The layer 4 examples are TCP, UDP, SPX

previous [page 5] next

[ Socialize This]

ISO's OSI Layered Model - Network Layer




The way that the data will be sent to the recipient device is determined in this layer. The famous Internet Protocol (IP) resides in this layer. The Internetwork Protocal identifies each host with a 32-bit IP address (for detail, see understanding subnet mask). IP is responsible for routing, directing datagrams from one network to another. It manages the connectionless transfer of data one hop at a time, from router to router. It is not responsible for reliable delivery to a next hop, but only for the detection of errored packets so they may be discarded. It is like a postal department, where the letter is passed from location to location, until it reaches the destination address on the envelope. The network layer may have to break large datagrams, larger than MTU, into smaller packets and host receiving the packet will have to reassemble the fragmented datagram.

Even though IP packets are addressed using IP addresses, hardware addresses must be used to actually transport data from one host to another. The DataLink layer protocal Address Resolution Protocol (ARP) is used to map the IP address to its hardware address.

In summary, the main functionality of network layer is routing and logical addressing, the data unit is packets, the network layer device is router and the network layer examples include IP, IPX, IPsec, ICMP, IGMP, OSPF, IGRP and EIGRP.

ISO's OSI Layered Model - DataLink Layer




The Data Link layer packages raw bits from the Physical layer into frames. This layer is responsible for transferring frames from one computer to another, without errors. A network data frame includes checksum, source and destination address, and data. The largest packet that can be sent through a data link layer defines the Maximum Transmission Unit (MTU).

The Data Link layer's functionality includes flow control, error detection and control, defining topologies such as star, bus, ring and media access control (MAC).

Ethernet addresses a host using a unique, 48-bit address called its Ethernet address or Media Access Control (MAC) address. MAC is closely associated with the physical layer and defines the means by which the physical medium may be accessed. MAC addresses are usually represented as six colon-separated pairs of hex digits, e.g., 8:0:20:11:ac:85. This number is unique and is associated with a particular Ethernet device; the first 3 bytes 8:0:20 specify the vendor/manufacturer of the NIC; the other 3 bytes 11:ac:85 define the host. The data link layer's protocolspecific header specifies the MAC address of the packet's source and destination. When a packet is sent to all hosts (broadcast), a special MAC address (ff:ff:ff:ff:ff:ff) is used.

The DataLink Layer Devices include switch, bridge.

DataLink Layer example include: 802.3, ATM, Frame Relay, PPP, Token Ring, ARP, SLIP

previous [page 3] next

[ Socialize This]

ISO's OSI Layered Model - Physical Layer




The first layer is the physical layer. This is the level of the actual hardware. It defines the physical characteristics of the network such as connections, voltage levels, transmission frequencies, timing, etc. The physical layer provides an unstructured bit stream, which is the phycial basis for all the higher layers.

Devices at this layer includes: Multiplexer, Repeater, hub, cable, network card, unshielded twisted pairs (UTP), etc.

Examples are Ethernet, RS-232, T1, DSL, etc.


previous [page 2] next


ISO's OSI Layered Model


The Open Systems Interconnection Reference Model (OSI Reference Model or OSI Model) is an abstract description for layered communications and computer network protocol design. It was developed as part of the Open Systems Interconnection (OSI) initiative. In its most basic form, it divides network architecture into seven layers which, from bottom to top, are the Physical, Data-Link, Network, Transport, Session, Presentation, Application Layers (Please Do Not Throw Sausage Pizza Away). It is therefore often referred to as the OSI Seven Layer Model.
Control is passed from one layer to the next, starting at the application layer in one station, proceeding to the bottom layer, over the channel to the next station and back up the hierarchy. Data exists at each layer in units called Protocal Data units (PDU). The picture gives the PDU at each layer.
previous [page 1] next


Why I stopped publishing blog posts as information provider

Now the AI can generate content. Does that mean the web publishing industry reaches the end? ChatGPT said: ChatGPT Not at all. While AI can ...