Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/articles/c-tutorials/)
-   -   Sockets in C Tutorials (http://www.go4expert.com/articles/sockets-c-tutorials-t24491/)

lionaneesh 11Jan2011 20:58

Sockets in C Tutorials
 

What is a socket?



See there are many types of sockets hardware sockets “like electrical sockets” etc. and software “programming sockets” like what i'm going to talk about from now onwards.

See , a socket can be thought like any standard way to perform network communication through our system to another system or multiple systems . In this course I'll be only talking about establishment of connection in between two machines.

Types of sockets with respect to programming:-



Socket definations in </usr/include/bits/socket.h>
Code:

/* Types of sockets.  */
enum __socket_type
{
  SOCK_STREAM = 1,                /* Sequenced, reliable, connection-based
                                  byte streams.  */
#define SOCK_STREAM SOCK_STREAM
  SOCK_DGRAM = 2,                /* Connectionless, unreliable datagrams
                                  of fixed maximum length.  */
#define SOCK_DGRAM SOCK_DGRAM
  SOCK_RAW = 3,                        /* Raw protocol interface.  */
#define SOCK_RAW SOCK_RAW
  SOCK_RDM = 4,                        /* Reliably-delivered messages.  */
#define SOCK_RDM SOCK_RDM
  SOCK_SEQPACKET = 5,                /* Sequenced, reliable, connection-based,
                                  datagrams of fixed maximum length.  */
#define SOCK_SEQPACKET SOCK_SEQPACKET
  SOCK_DCCP = 6,                /* Datagram Congestion Control Protocol.  */
#define SOCK_DCCP SOCK_DCCP
  SOCK_PACKET = 10,                /* Linux specific way of getting packets
                                  at the dev level.  For writing rarp and
                                  other similar things on the user level. */
#define SOCK_PACKET SOCK_PACKET

  /* Flags to be ORed into the type parameter of socket and socketpair and
    used for the flags parameter of paccept.  */

  SOCK_CLOEXEC = 02000000,        /* Atomically set close-on-exec flag for the
                                  new descriptor(s).  */
#define SOCK_CLOEXEC SOCK_CLOEXEC
  SOCK_NONBLOCK = 04000                /* Atomically mark descriptor(s) as
                                  non-blocking.  */
#define SOCK_NONBLOCK SOCK_NONBLOCK
};

There are basically two commonly used sockets in programming they are :-
  1. Stream sockets
  2. UDP datagram sockets
Note:-These are not the only two sockets in the programming but the most commonly used there are tons of more like Raw sockets etc etc.. and I also don't know much about them. You'll learn about them in advance level but these two are great for building up the basics. At-least I think so [ : | ] …


Stream sockets:-



They are basically connection oriented reliable 2 way communication sockets. Having problem understanding that one ..
Its Ok!! i'll make it simple.

Call your friend through the phone and notice your friend receives the request in the form of a call then as he picks up both sides initiates the connection to one other and after the connection is established and each side can communicate to each other. In addition there is a confirmation that the words you speak actually reaches the other side.


Now I think you'll find it easy to gasp up.

Stream sockets use TCP/IP protocol a tutorial on this can be found on http://www.w3schools.com/tcpip/tcpip_intro.asp or i'll write a tutorial on it soon...

Drawbacks of stream sockets:-



They are two way connection sockets and they are slower in terms of sending and receiving than Datagram sockets because when we send a packet through Stream sockets it will send it and then ensure that is it reached or not then It will send back the confirmation message.
Quite a long way right...

To avoid this drawback our network gurus invented “THE DATAGRAM SOCKETS” yupii!!! ….LOL...

We'll talk about them right down there...

ok. Now let us come to the Datagram sockets …

Datagram sockets:-



What is a datagram sockets is that they are the one-way, non-reliable connectionless sockets . Yeah I'll make it easy..

Now imagine you are mailing [ not e-mailing ] a letter to your old friend staying overseas through not a very good company . You are not sure that will it reach to its destination or not. Yeah you are right out mailing service providers are quite reliable but the net is not.

So why do we need them then... “man they are useless” no my friend these are also very important sockets in some programs ..
some common programs using datagram sockets are :-

Softwares dealing with network games , streaming media , etc etc....because packet loss is acceptable but loss of speed unacceptable.

Disadvantages of Datagram sockets:-



These are non-reliable.. and are one-way connection based.

Protocols



As per as defined in </usr/include/bits/socket.h> there are the following types of protocols :-

Code:

/* Protocol families.  */
#define        PF_UNSPEC        0        /* Unspecified.  */
#define        PF_LOCAL        1        /* Local to host (pipes and file-domain).  */
#define        PF_UNIX                PF_LOCAL /* POSIX name for PF_LOCAL.  */
#define        PF_FILE                PF_LOCAL /* Another non-standard name for PF_LOCAL.  */
#define        PF_INET                2        /* IP protocol family.  */
#define        PF_AX25                3        /* Amateur Radio AX.25.  */
#define        PF_IPX                4        /* Novell Internet Protocol.  */
#define        PF_APPLETALK        5        /* Appletalk DDP.  */
#define        PF_NETROM        6        /* Amateur radio NetROM.  */
#define        PF_BRIDGE        7        /* Multiprotocol bridge.  */
#define        PF_ATMPVC        8        /* ATM PVCs.  */
#define        PF_X25                9        /* Reserved for X.25 project.  */
#define        PF_INET6        10        /* IP version 6.  */
#define        PF_ROSE                11        /* Amateur Radio X.25 PLP.  */
#define        PF_DECnet        12        /* Reserved for DECnet project.  */
#define        PF_NETBEUI        13        /* Reserved for 802.2LLC project.  */
#define        PF_SECURITY        14        /* Security callback pseudo AF.  */
#define        PF_KEY                15        /* PF_KEY key management API.  */
#define        PF_NETLINK        16
#define        PF_ROUTE        PF_NETLINK /* Alias to emulate 4.4BSD.  */
#define        PF_PACKET        17        /* Packet family.  */
#define        PF_ASH                18        /* Ash.  */
#define        PF_ECONET        19        /* Acorn Econet.  */
#define        PF_ATMSVC        20        /* ATM SVCs.  */
#define PF_RDS                21        /* RDS sockets.  */
#define        PF_SNA                22        /* Linux SNA Project */
#define        PF_IRDA                23        /* IRDA sockets.  */
#define        PF_PPPOX        24        /* PPPoX sockets.  */
#define        PF_WANPIPE        25        /* Wanpipe API sockets.  */
#define PF_LLC                26        /* Linux LLC.  */
#define PF_CAN                29        /* Controller Area Network.  */
#define PF_TIPC                30        /* TIPC sockets.  */
#define        PF_BLUETOOTH        31        /* Bluetooth sockets.  */
#define        PF_IUCV                32        /* IUCV sockets.  */
#define PF_RXRPC        33        /* RxRPC sockets.  */
#define PF_ISDN                34        /* mISDN sockets.  */
#define PF_PHONET        35        /* Phonet sockets.  */
#define PF_IEEE802154        36        /* IEEE 802.15.4 sockets.  */
#define        PF_MAX                37        /* For now..  */

Hey .. Don't be scared you don't have to know all about them until you get 1-2 year experienced programmer in C ..Ok!! so Chill....

So , in all of the above the ones we are interested in are the
Code:

#define        PF_UNSPEC        0        /* Unspecified.  */
#define        PF_INET                2        /* IP protocol family.  */
#define        PF_INET6        10        /* IP version 6.  */

Structs and declarations :-



First of all i'll tell you what are the actual role of these structures in our programming.. See these structures are the ones who so all the stuff to send receive data in and out . We just fill out these structures and the rest is all to just sit and watch your program work! Wait! I'm not saying that all the work done is by the structs .No. These structs are accompanied by some functions which I will mention later in this guide...

Struct sockaddr:-

Code:

/* Structure describing a generic socket address.  */
struct sockaddr
  {
    __SOCKADDR_COMMON (sa_);        /* Common data: address family and length.  */
    char sa_data[14];                /* Address data.  */
  };

The comment on the above says it all it is a structure describing a generic socket address. The sockaddr_common can be any thing but in this document we'll be dealing with AF_INET or AF_INET6.
And sa_data contains a destination address and port number for the
socket. This is rather unwieldy since you don't want to tediously pack the address in the sa_data by hand. The functions will do that for you...

struct sockaddr_in:-

Code:

    struct sockaddr_in
{
    short int          sin_family;  // Address family, AF_INET
    unsigned short int sin_port;    // Port number
    struct in_addr    sin_addr;    // Internet address
    unsigned char      sin_zero[8]; // Same size as struct sockaddr
};

As we've read above that there are 2 ip versions till date and this structure only handles IPV4 .No need to worry about this our functions will fill up the structure we'll talk about these functions in the next section.

In the above structure :-
Code:

struct in_addr    sin_addr;    // Internet address
This will give us the IP address of the remote computer in the network byte order we have to convert iy to presentation to make it readable. I'll tell you how in the next section. So , stick in there.

To deal with Some Ipv6 addresses our NETWORK GURUS

Code:


// (IPv6 only--see struct sockaddr_in and struct in_addr for IPv4)
struct sockaddr_in6
{
    u_int16_t      sin6_family;  // address family, AF_INET6
    u_int16_t      sin6_port;    // port number, Network Byte Order
    u_int32_t      sin6_flowinfo; // IPv6 flow information
    struct in6_addr sin6_addr;    // IPv6 address
    u_int32_t      sin6_scope_id; // Scope ID
};
struct in6_addr
{
        unsigned char  s6_addr[16];  // IPv6 address
};

Just little bit different from the structure sockaddr_in. This sturcture deals with IPV6 …

This struct is commented enough for your understanding .
I'll explain this with more detail when we'll make our programs.

Structure Sockaddr_storage

Code:

struct sockaddr_storage {
    sa_family_t ss_family;      // address family
    // all this is padding, implementation specific, ignore it:
    char      __ss_pad1[_SS_PAD1SIZE];
    int64_t  __ss_align;
    char      __ss_pad2[_SS_PAD2SIZE];
};

This structure looks quite simmilar to the sockaddr_in structure but this structure is made big enough to hold both IPV4 and IPV6 values...


Struct addrinfo:-
Code:

struct addrinfo {
    int              ai_flags;    // AI_PASSIVE, AI_CANONNAME, etc.
    int              ai_family;    // AF_INET, AF_INET6, AF_UNSPEC
    int              ai_socktype;  // SOCK_STREAM, SOCK_DGRAM
    int              ai_protocol;  // use 0 for "any"
    size_t          ai_addrlen;  // size of ai_addr in bytes
    struct sockaddr *ai_addr;      // struct sockaddr_in or _in6
    char            *ai_canonname; // full canonical hostname
    struct addrinfo *ai_next;      // linked list, next node
};

We'll be using this structure the most during this short course so pay some respect to it... LOL … just kiddin...

This structure is simply used for a function getaddrinfo() which i'll get to in a minute!!!

Functions



To make our work easier our C network gurus created some top class functions to automate the automation …

yeah! So here they come :-
  1. getaddrinfo() … The most important function for me .. while programming Sockets.
  2. socket()
  3. bind() // Only for the server side
  4. accept //Only for the server side
  5. connect() // The client side
  6. listen() // Server side
  7. send()
  8. recv()
  9. sendto() // only for Dgram
  10. recvfrom() // only for dgram
  11. close()
  12. Shutdown()
  13. getpeerbyname()
  14. gethostbyname()
Most probably i'l cover these functions with explanations in my next tutorial...Till then read the man pages ...Figure out some stuff and post it here...

Conclusion



Thanks for viewing this tutorial...
Please try and leave a comment or thanks...

lionaneesh 13Jan2011 12:34

Re: Sockets in C Tutorials
 
It would be gr8 if the viewers could comment!!!!!

Seo_Aryan 18Jan2011 17:09

Re: Sockets in C Tutorials
 
Most interprocess communication uses the client server model. These terms refer to the two processes which will be communicating with each other. One of the two processes, the client, connects to the other process, the server, typically to make a request for information. A good analogy is a person who makes a phone call to another person.

Notice that the client needs to know of the existence of and the address of the server, but the server does not need to know the address of (or even the existence of) the client prior to the connection being established.

Notice also that once a connection is established, both sides can send and receive information.

The system calls for establishing a connection are somewhat different for the client and the server, but both involve the basic construct of a socket.
A socket is one end of an interprocess communication channel. The two processes
each establish their own socket.

The steps involved in establishing a socket on the client side are as follows:

1. Create a socket with the socket() system call
2. Connect the socket to the address of the server using the connect() system call
3. Send and receive data. There are a number of ways to do this, but the simplest is to use the read() and write() system calls.

The steps involved in establishing a socket on the server side are as follows:

1. Create a socket with the socket() system call
2. Bind the socket to an address using the bind() system call. For a server socket on the Internet, an address consists of a port number on the host machine.
3. Listen for connections with the listen() system call
4. Accept a connection with the accept() system call. This call typically blocks until a client connects with the server.
5. Send and receive data

lionaneesh 18Jan2011 17:21

Re: Sockets in C Tutorials
 
Quote:

Originally Posted by Seo_Aryan (Post 77719)
Most interprocess communication uses the client server model. These terms refer to the two processes which will be communicating with each other. One of the two processes, the client, connects to the other process, the server, typically to make a request for information. A good analogy is a person who makes a phone call to another person.

Notice that the client needs to know of the existence of and the address of the server, but the server does not need to know the address of (or even the existence of) the client prior to the connection being established.

Notice also that once a connection is established, both sides can send and receive information.

The system calls for establishing a connection are somewhat different for the client and the server, but both involve the basic construct of a socket.
A socket is one end of an interprocess communication channel. The two processes
each establish their own socket.

The steps involved in establishing a socket on the client side are as follows:

1. Create a socket with the socket() system call
2. Connect the socket to the address of the server using the connect() system call
3. Send and receive data. There are a number of ways to do this, but the simplest is to use the read() and write() system calls.

The steps involved in establishing a socket on the server side are as follows:

1. Create a socket with the socket() system call
2. Bind the socket to an address using the bind() system call. For a server socket on the Internet, an address consists of a port number on the host machine.
3. Listen for connections with the listen() system call
4. Accept a connection with the accept() system call. This call typically blocks until a client connects with the server.
5. Send and receive data

Thanks for commenting and sharing what you know...

sneha123 21Jan2011 15:55

Re: Sockets in C Tutorials
 
Hello to all,,,,,sneha here...........I agree this comment...I like it,,,,,,,
"The steps involved in establishing a socket on the server side are as follows:

1. Create a socket with the socket() system call
2. Bind the socket to an address using the bind() system call. For a server socket on the Internet, an address consists of a port number on the host machine.
3. Listen for connections with the listen() system call
4. Accept a connection with the accept() system call. This call typically blocks until a client connects with the server.
5. Send and receive data."..........thanks for share with us,,,,,:crazy::crazy:

lionaneesh 23Jan2011 00:05

Re: Sockets in C Tutorials
 
Quote:

Originally Posted by sneha123 (Post 77927)
Hello to all,,,,,sneha here...........I agree this comment...I like it,,,,,,,
&quot;The steps involved in establishing a socket on the server side are as follows:

1. Create a socket with the socket() system call
2. Bind the socket to an address using the bind() system call. For a server socket on the Internet, an address consists of a port number on the host machine.
3. Listen for connections with the listen() system call
4. Accept a connection with the accept() system call. This call typically blocks until a client connects with the server.
5. Send and receive data.&quot;..........thanks for share with us,,,,,:crazy::crazy:

Hey One thing i would like you to know... Is that :- Please dont use ""[quotes] while excerpting a comment ... Use Quote... At the ending of every comment there is a button on the right bottom nameed 'Quote' click that and You will be redirected to a page then you can write your message from there on!!! I hope You Understood!!

hamed2012 23Jan2011 16:06

Re: Sockets in C Tutorials
 
hello
i need socket.h & ...
please help me

lionaneesh 23Jan2011 16:09

Re: Sockets in C Tutorials
 
Quote:

Originally Posted by hamed2012 (Post 78056)
hello
i need socket.h & ...
please help me

If you are using Unix... There is no need to install it its already here... And this program can only be run in Unix...

sneha123 24Jan2011 11:08

Re: Sockets in C Tutorials
 
Quote:

Originally Posted by lionaneesh (Post 78044)
Hey One thing i would like you to know... Is that :- Please dont use ""[quotes] while excerpting a comment ... Use Quote... At the ending of every comment there is a button on the right bottom nameed 'Quote' click that and You will be redirected to a page then you can write your message from there on!!! I hope You Understood!!

Hello sir,,,,I really thankful to you for reply my post and you suggest me,,,,,thanks lot,,,,,,,
with regards,,,
sneha123

lionaneesh 24Jan2011 15:38

Re: Sockets in C Tutorials
 
Quote:

Originally Posted by sneha123 (Post 78083)
Hello sir,,,,I really thankful to you for reply my post and you suggest me,,,,,thanks lot,,,,,,,
with regards,,,
sneha123

Always welcome!!!

_st4ck3D* 11Feb2011 18:11

Re: Sockets in C Tutorials
 
Well done written.

lionaneesh 11Feb2011 18:27

Re: Sockets in C Tutorials
 
Quote:

Originally Posted by _st4ck3D* (Post 79137)
Well done written.

Thanks a ton...


All times are GMT +5.5. The time now is 19:36.