PoiNtEr->: June 2012

                             Difference between a dream and an aim. A dream requires soundless sleep, whereas an aim requires sleepless efforts.

Search This Blog

Wednesday, June 27, 2012

Socket programming in C


This is a quick tutorial to learning socket programming in C language on a Ubuntu system. “Ubuntu” because the code snippets shown over here will work only on a Linux system and not on Windows. 

Socket
Sockets are the fundamental “things” behind any kind of network communications done by your computer. For example when you type www.vishalmishra.tk in your web browser, it opens a socket and connects to www.vishalmishra.tk to fetch the page and show it to you. 
A network socket is an endpoint of an inter-process communication flow across a computer network. Today, most communication between computers is based on the Internet Protocol; therefore most network sockets are Internet sockets.
An Internet socket is characterized by a unique combination of the following:Local socket address: Local IP address and port numberRemote socket address: Only for established TCP sockets. As discussed in the client-server section below, this is necessary since a TCP server may serve several clients concurrently. The server creates one socket for each client, and these sockets share the same local socket address.Protocol: A transport protocol (e.g., TCP, UDP, raw IP, or others). TCP port 53 and UDP port 53 are consequently different, distinct sockets.Within the operating system and the application that created a socket, the socket is referred to by a unique integer number called socket identifier or socket number. The operating system forwards the payload of incoming IP packets to the corresponding application by extracting the socket address information from the IP and transport protocol headers and stripping the headers from the application data.
Socket types
There are several Internet socket types available:
Datagram sockets, also known as connectionless sockets, which use User Datagram Protocol (UDP)
Stream sockets, also known as connection-oriented sockets, which use Transmission Control Protocol (TCP) or Stream Control Transmission Protocol (SCTP).
Raw sockets (or Raw IP sockets), typically available in routers and other network equipment. Here the transport layer is bypassed, and the packet headers are made accessible to the application.
Creating a socket
This first thing to do is create a socket. The socket() function does this.
Here is a code sample :
#include<stdio.h>
#include<sys/socket.h>
int main(int argc , char *argv[])
{
int socket_desc;socket_desc = socket(AF_INET , SOCK_STREAM , 0);
if (socket_desc == -1)
{
printf("Could not create socket");
}
return 0;
}
Function socket() creates a socket and returns a socket descriptor which can be used in other network commands. The above code will create a socket of :
Address Family : AF_INET (this is IP version 4)
Type : SOCK_STREAM (this means connection oriented TCP protocol)
Protocol : 0 [ or IPPROTO_IP This is IP protocol]Ok , so you have created a socket successfully. But what next ?
Now  we shall try to connect to some server using this socket. 
Connect to a Server
We connect to a remote server on a certain port number. So we need 2 things , IP address and port number to connect to.To connect to a remote server we need to do a couple of things. First is create a sockaddr_in structure with proper values filled in. Lets create one for ourselves :
struct sockaddr_in server;
Have a look at the structure
// IPv4 AF_INET sockets:
struct sockaddr_in {
    short            sin_family;   // e.g. AF_INET, AF_INET6
    unsigned short   sin_port;     // e.g. htons(3490)
    struct in_addr   sin_addr;     // see struct in_addr, below
    char             sin_zero[8];  // zero this if you want to
};

struct in_addr {
    unsigned long s_addr;          // load with inet_pton()
};

struct sockaddr {
    unsigned short    sa_family;    // address family, AF_xxx
    char              sa_data[14];  // 14 bytes of protocol address
};

The sockaddr_in has a member called sin_addr of type in_addr which has a s_addr which is nothing but a long. It contains the IP address in long format.
Function inet_addr is a very handy function to convert an IP address to a long format. This is how you do it :
server.sin_addr.s_addr = inet_addr("46.51.216.186");
So you need to know the IP address of the remote server you are connecting to. Here we used the ip address of duckduckgo.com as a sample. A little later on we shall see how to find out the ip address of a given domain name.
The last thing needed is the connect function. It needs a socket and a sockaddr structure to connect to. Here is a code sample.
#include<stdio.h>
#include<sys/socket.h>
#include<arpa/inet.h> //inet_addr

int main(int argc , char *argv[])
{
 int socket_desc;
 struct sockaddr_in server;
 
 //Create socket
 socket_desc = socket(AF_INET , SOCK_STREAM , 0);
 if (socket_desc == -1)
 {
  printf("Could not create socket");
 }
  
 server.sin_addr.s_addr = inet_addr("46.51.216.186");
 server.sin_family = AF_INET;
 server.sin_port = htons( 80 );

 //Connect to remote server
 if (connect(socket_desc , (struct sockaddr *)&server , sizeof(server)) < 0)
 {
  puts("connect error");
  return 1;
 }
 
 puts("Connected");
 return 0;
}
It cannot be any simpler. It creates a socket and then connects. If you run the program it should show Connected.
Try connecting to a port different from port 80 and you should not be able to connect which indicates that the port is not open for connection.
Now in next post we will see how to send some data to remote server.

Thursday, June 21, 2012

Microcontroller-The Basics

A microcontroller (sometimes abbreviated µC, uC or MCU) is a small computer on a single integrated circuit containing a processor core, memory, and programmable input/output peripherals. Program memory in the form of NOR flash or OTP ROM is also often included on chip, as well as a typically small amount of RAM. Microcontrollers are designed for embedded applications, in contrast to the microprocessors used in personal computers or other general purpose applications.


The obvious question should be answered first. The word microcontroller is similar to the word microprocessor which is the core of modern computers.

Micro means something very small or tiny. The integrated circuits are fabricated in very small chips which have made our modern computers smaller.

Controller means something which has the ability to control. For example, deciding how much amount of heat to maintain in a microwave oven when it is set to run on auto cook modes or a worker robot which has to decide which box to put in which truck.

Both the oven and the robot need some sort of thing which can make these decisions for them. Otherwise both of them are going to be useless. Another example can be a cell phone. It shows its battery level, warns us if the battery is low. When the charge is full, it tells us to
remove the charger. Which ghost is responsible for that?

The answer is obvious, Microcontroller.
Microcontroller

A Microcontroller is a chip which has the capability to decide and control situations according to the instructions provided by its user. The word Microcontroller is abbreviated as uC or MCU (Micro Controller Unit). We will sometimes refer to it as uC or MCU.

Where and why we need a Microcontroller?
Any system that needs some sort of automated control uses Microcontrollers. Actually we are using uC everyday even though we are not aware of them. For example, Modern Televisions, Cell Phones, Microwave Ovens, Washing Machines, Cars, Toys, Airplanes, Battery Chargers, Inverters and specially Robots. If you want to give your equipment a sophisticated ‘Brain’ so that it can monitor situations, process calculations and take decisions according to your requirement, you need to use a uC. It is the “Brain” of a robot.


A Microcontroller is just like a computer.

Difference between a Computer and a Microcontroller
After you have read up to this portion of the chapter, one question might come to your mind. What is the difference between the PCs we use in our daily life and the Microcontrollers? Well, there is more similarity then the differences. But there are significant differences which explain a uC being priced at as low as 60-100.

In a computer, we put on the processor on the motherboard. We also install RAM modules, Hard Discs etc. The motherboard contains the ROM that initiates the BIOS (Basic Input Output System).

Unlike Microprocessors, the Microcontrollers have everything that is required to perform its operation are built in a single package. That means a single MCU contains the processor, RAM, ROM, Flash Memory. All are included in a single chip. So a Microcontroller resembles a complete computer, well of course in a tiny format.

A Sample Microcontroller
A Sample Computer
Clock Speed
16MHz
3.0 GHz
Program Storage
8 kilobyte Flash
500 Gigabyte Hard Disc
RAM
1 kilobyte
2 Gigabyte
The comparison reveals a major difference. Don’t underestimate the uC. It may not be adequate for encoding your HD videos but is great for our computing requirements in the circuits we might implement. For most applications we don’t need more than that. 
So, we are getting a computer in a tiny package. That’s why MCUs are simple to use and very cheap compared to a PC. Microcontrollers can process quite complex functions, data manipulations and DSP algorithms. The data shown here are just for an ordinary MCU; there are more powerful MCUs available in the markets.

Friday, June 8, 2012

Install and Configure Telnet Server in Ubuntu-12.04


You will find the Telnet server installation packages in Synaptic under the telnetd package.If you want to install telnet server package you can also use the following command


sudo apt-get install xinetd telnetd


This will complete the installation.Now you Restart inetd service using the following command


sudo /etc/init.d/inetd restart


Once installed now go to terminal and follow following instruction
1:Create /etc/inetd.conf ,if it already exist then no need to create just open it with your favorite editor


sudo vi /etc/inetd.conf


add following line in it if its already there then uncomment it: 

telnet         stream  tcp     nowait  telnetd.telnetd /usr/sbin/tcpd  /usr/sbin/in.telnetd

you can now fire up your other Linux box and type telnet . You are prompted to enter your username and password. The whole conversation should look like this



vishal@Eva:~$ telnet localhost
Trying 192.168.2.200...
Connected to localhost.
Escape character is '^]'.
Ubuntu 12.04 LTS
Eva.localhost login: vishal
Password: 
Last login: Wed Jun  6 12:26:51 IST 2012 on tty2
Welcome to Ubuntu 12.04 LTS (GNU/Linux 2.6.38-10-generic i686)


 * Documentation:  https://help.ubuntu.com/


75 packages can be updated.
25 updates are security updates.


*** /dev/sda5 will be checked for errors at next reboot ***


You have new mail.
vishal@Eva:~$ 

you can also try it from other system or from virtual machine(xp or any) to connect by using 
“telnet ip address” of linux machine which is running telnet sever,after this it will ask you for login and thats it !!

Note that the server responds with Welcome to telnetserver, running Ubuntu LAMP server, which is a customized message. Your machine will probably respond with Ubuntu and some version information. This is insecure: giving away version numbers is never a smart move. In fact, even saying Ubuntu is questionable. Edit the issue and issue.net files in your /etc directory to change these messages.
Running the w command now shows you as connecting from the external IP address.
like:

vishal@Eva:~$ w
 12:36:11 up  2:47,  4 users,  load average: 0.58, 0.47, 0.65
USER     TTY      FROM              LOGIN@   IDLE   JCPU   PCPU WHAT
vishal   pts/1    :0               10:05   43:05   0.40s  2:21  gnome-terminal
vishal   pts/4    :0               11:53   42:57   0.82s  2:21  gnome-terminal
vishal   pts/5    localhost    12:35    0.00s  0.75s  0.01s w
vishal   pts/6    :0               12:16    0.00s  0.44s  0.00s telnet localhost