PoiNtEr->: Socket programming in C

                             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.

No comments:

Post a Comment