Friday, March 27, 2009

socket programming basics in 'C'

Socket:
a socket is a simple program that enables communication b/w two different computers or with in a computer itself .each socket has a name except nameless socket .

Types of socket :
1.Nameless socket or local socket or unix domain socket :
they do not hv any addrss becoz they connect wid in m/c itself
uses AF_LOCAL prefix
A-> address
F->family
Function used: socketpair()
2.Internet domain socket :used for process running on multiple computers
uses PF_INET macro
P->protocol
F->family
Function used: socket()
FOR EXAMPLE:
Functio and header file used for creating a nameless socket:

#include
#include
{
int socketpair(int domain, int type , int protocol ,int ds[2]);
}
on success of this function zero is returned and on failure -1 is returned wid error number.

for linux only supprted DOMAIN is AF_UNIX or AF_LOCAL
TYPE:
1.SOCK_STREAM: for a connection oriented socket,out of band data
2.SOCK_DGRAM:for connection less socket
3.SOCK_SEQPACKET:connection oriented ,reliable and connection boundries are visible.

PROTOCOL: to be used is either TCP or UDP, zero argument 'll let let the OS decide automatically reqd protocol
DS[2]:it is a two element array each representing a socket or end point.

I/O on socket:
#include
{
ssize_t read(int fd,void *buff ,size_t length);
ssize_t write(int fd ,const void * buff,size_t length);
int close(int fd);
}
return value of r/w functions provides actual no of bytes read and write respectively.
size_t provides max size of the buffer
return value zero indicates succes while -1 indicates failure.

Closing a socket:
int shutdown(int socket , int how ) ;
socket: defines socket descriptor to be shutdown
how:
0 : OR SHUT_RD NO MORE READ
1 : OR SHUT_WR NO MORE WRITE
2: OR SHUT_RDWR NO MORE READ OR WRITE



No comments: