Saturday, 27 June 2015


Sockets allow communication between two different processes on the same or different machines. To be more precise, it's a way to talk to other computers using standard Unix file descriptors. In Unix, every I/O action is done by writing or reading a file descriptor. A file descriptor is just an integer associated with an open file and it can be a network connection, a text file, a terminal, or something else.
To a programmer, a socket looks and behaves much like a low-level file descriptor. This is because commands such as read() and write() work with sockets in the same way they do with files and pipes.
Where is Socket Used?
A Unix Socket is used in a client-server application framework. A server is a process that performs some functions on request from a client. Most of the application-level protocols like FTP, SMTP, and POP3 make use of sockets to establish connection between client and server and then for exchanging data.
int socket(int domain, int type, int protocol)
Here., Domain refers to: Socket Family
Protocol refers to: The type of Protocol we want to use
Type refers to: Socket Service Type
Socket Service Types:
The following socket types are defined,The first two are most commonly used and the last two are rarely used.
Processes are presumed to communicate only between sockets of the same type but there is no restriction that prevents communication between sockets of different types.
  • Stream Sockets(SOCK_STREAM): Delivery in a networked environment is guaranteed. If you send through the stream socket three items "A, B, C", they will arrive in the same order - "A, B, C". These sockets use TCP (Transmission Control Protocol) for data transmission. If delivery is impossible, the sender receives an error indicator. Data records do not have any boundaries.
  • Datagram Sockets(SOCK_DGRAM): Delivery in a networked environment is not guaranteed. They're connectionless because you don't need to have an open connection as in Stream Sockets - you build a packet with the destination information and send it out. They use UDP (User Datagram Protocol).
  • Raw Sockets(SOCK_RAW): These provide users access to the underlying communication protocols, which support socket abstractions. These sockets are normally datagram oriented, though their exact characteristics are dependent on the interface provided by the protocol. Raw sockets are not intended for the general user; they have been provided mainly for those interested in developing new communication protocols, or for gaining access to some of the more cryptic facilities of an existing protocol.
  • Sequenced Packet Sockets(SOCK_SEQPACKET): They are similar to a stream socket, with the exception that record boundaries are preserved. This interface is provided only as a part of the Network Systems (NS) socket abstraction, and is very important in most serious NS applications. Sequenced-packet sockets allow the user to manipulate the Sequence Packet Protocol (SPP) or Internet Datagram Protocol (IDP) headers on a packet or a group of packets, either by writing a prototype header along with whatever data is to be sent, or by specifying a default header to be used with all outgoing data, and allows the user to receive the headers on incoming packets.
    Embedded Systems Training

Thursday, 25 June 2015

TCP/IP Protocol Architecture

TCP/IP protocols map to a four-layer conceptual model known as the DARPA model , named after the U.S. government agency that initially developed TCP/IP. The four layers of the DARPA model are: Application, Transport, Internet, and Network Interface. Each layer in the DARPA model corresponds to one or more layers of the seven-layer Open Systems Interconnection (OSI) model.

Figure 1.1 shows the TCP/IP protocol architecture.

Figure 1.1 TCP/IP Protocol Architecture
Network Interface Layer
The Network Interface layer (also called the Network Access layer) is responsible for placing TCP/IP packets on the network medium and receiving TCP/IP packets off the network medium. TCP/IP was designed to be independent of the network access method, frame format, and medium. In this way, TCP/IP can be used to connect differing network types. These include LAN technologies such as Ethernet and Token Ring and WAN technologies such as X.25 and Frame Relay. Independence from any specific network technology gives TCP/IP the ability to be adapted to new technologies such as Asynchronous Transfer Mode (ATM).
The Network Interface layer encompasses the Data Link and Physical layers of the OSI model. Note that the Internet layer does not take advantage of sequencing and acknowledgment services that might be present in the Data-Link layer. An unreliable Network Interface layer is assumed, and reliable communications through session establishment and the sequencing and acknowledgment of packets is the responsibility of the Transport layer.

Internet Layer
The Internet layer is responsible for addressing, packaging, and routing functions. The core protocols of the Internet layer are IP, ARP, ICMP, and IGMP.
  • The Internet Protocol (IP) is a routable protocol responsible for IP addressing, routing, and the fragmentation and reassembly of packets.
  • The Address Resolution Protocol (ARP) is responsible for the resolution of the Internet layer address to the Network Interface layer address such as a hardware address.
  • The Internet Control Message Protocol (ICMP) is responsible for providing diagnostic functions and reporting errors due to the unsuccessful delivery of IP packets.
  • The Internet Group Management Protocol (IGMP) is responsible for the management of IP multicast groups.
The Internet layer is analogous to the Network layer of the OSI model.

Transport Layer
The Transport layer (also known as the Host-to-Host Transport layer) is responsible for providing the Application layer with session and datagram communication services. The core protocols of the Transport layer are Transmission Control Protocol (TCP) and the User Datagram Protocol (UDP).
  • TCP provides a one-to-one, connection-oriented, reliable communications service. TCP is responsible for the establishment of a TCP connection, the sequencing and acknowledgment of packets sent, and the recovery of packets lost during transmission.
  • UDP provides a one-to-one or one-to-many, connectionless, unreliable communications service. UDP is used when the amount of data to be transferred is small (such as the data that would fit into a single packet), when the overhead of establishing a TCP connection is not desired or when the applications or upper layer protocols provide reliable delivery.
The Transport layer encompasses the responsibilities of the OSI Transport layer and some of the responsibilities of the OSI Session layer.

Application Layer
The Application layer provides applications the ability to access the services of the other layers and defines the protocols that applications use to exchange data. There are many Application layer protocols and new protocols are always being developed.
The most widely-known Application layer protocols are those used for the exchange of user information:
  • The Hypertext Transfer Protocol (HTTP) is used to transfer files that make up the Web pages of the World Wide Web.
  • The File Transfer Protocol (FTP) is used for interactive file transfer.
  • The Simple Mail Transfer Protocol (SMTP) is used for the transfer of mail messages and attachments.
  • Telnet, a terminal emulation protocol, is used for logging on remotely to network hosts.
Additionally, the following Application layer protocols help facilitate the use and management of TCP/IP networks:
  • The Domain Name System (DNS) is used to resolve a host name to an IP address.
  • The Routing Information Protocol (RIP) is a routing protocol that routers use to exchange routing information on an IP internetwork.
  • The Simple Network Management Protocol (SNMP) is used between a network management console and network devices (routers, bridges, intelligent hubs) to collect and exchange network management information.
Examples of Application layer interfaces for TCP/IP applications are Windows Sockets and NetBIOS

Sunday, 21 June 2015

Struct Hack in C

“Struct Hack” technique is used to create variable length member in a structure
struct employee
int emp_id;
int  name_len;
char name[1];
In gcc, when we create an array of length 1, it is considered as array of incomplete type.This technique is known as “Stuct Hack”. When we create array of variable length inside structure, it must be (and only) last member of structure.
Let us see below memory allocation.
struct employee *e = malloc(sizeof(*e) + sizeof(char) * 128);
is equivalent to
struct employee
int emp_id;
int  name_len;
char name[128]; /* character array of size 128 */

When we allocate memory as given above, compiler will allocate memory to store “emp_id” and “name_len” plus contiguous memory to store “name”. When we use this technique, gcc guaranties that, “name” will get contiguous memory.
Now we can use “name” same as pointer. e.g.
e->emp_id       = 100;
e->name_len     = strlen("Geeks For Geeks");
strncpy(e->name, "Geeks For Geeks", e->name_len);
Why not use a pointer?

struct Foo
  // ..
  size_t size;
  // data = (int*)malloc(sizeof(int) * 10);
  int *data;
The advantage of using an array is that you don’t have to allocate the memory elsewhere and make the pointer point to that. Thus there is no extra memory management. Furthermore, accesses to the memory will hit the memory cache (much) more likely because dynamically allocated block is contiguous.
Advantage of contiguous memory:

For example, by using this technique, we can allocate and deallocate memory by using single malloc and free call (because memory is contagious). Other advantage of this is, suppose if we want to write data, we can write whole data by using single “write()” call. e.g.
write(fd, e, sizeof(*e) + name_len); /* write emp_id + name_len + name */
If we use character pointer, then we need 2 write calls to write data. e.g.
write(fd, e, sizeof(*e));               /* write emp_id + name_len */
write(fd, e->name, e->name_len);        /* write name */
Note: In C99, there is feature called “flexible array members”, which works same as “Struct Hack”

Flexible array member:

C99 has a new language feature called “flexible array member”. It’s quite similar to the struct hack except an empty bracket [].
struct Foo
  size_t size;
  int data[]; // FLA
struct mystruct {
        int len;
        char chararray[1];  // some compilers would allow [0] here
    char *msg = "abcdefghi";
    int n = strlen (msg);
    struct mystruct *ptr = malloc(sizeof(struct mystruct) + n + 1);
    ptr->len = n;
    strcpy (ptr->chararray, msg);