Typically two processes communicate with each other on a single system through one of the following inter process communication techniques.

  • Pipes
  • Message queues
  • Shared memory

There are several other methods. But the above are some of the very classic ways of interprocess communication.

But have you ever given a thought over how two processes communicate across a network?

For example, when you browse a website, on your local system the process running is your web browser, while on the remote system the process running is the web server. So this is also an inter process communication but the technique through which they communicate with each other is SOCKETS, which is the focus of this article.

What is a SOCKET?

In layman’s term, a Socket is an end point of communication between two systems on a network. To be a bit precise, a socket is a combination of IP address and port on one system. So on each system a socket exists for a process interacting with the socket on other system over the network. A combination of local socket and the socket at the remote system is also known a ‘Four tuple’ or ’4-tuple’. Each connection between two processes running at different systems can be uniquely identified through their 4-tuple.

There are two types of network communication models:

  1. OSI
  2. TCP/IP

While OSI is more of a theoretical model, the TCP/IP networking model is the most popular and widely used.

 

As explained in our TCP/IP Fundamentals article, the communication over the network in TCP/IP model takes place in form of a client server architecture. ie, the client begins the communication and server follows up and a connection is established.

Sockets can be used in many languages like Java, C++ etc but here in this article, we will understand the socket communication in its purest form (i.e in C programming language)

Lets create a server that continuously runs and sends the date and time as soon as a client connects to it.

Socket Server Example

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <time.h> int main(int argc, char *argv[])
{
int listenfd = , connfd = ;
struct sockaddr_in serv_addr; char sendBuff[];
time_t ticks; listenfd = socket(AF_INET, SOCK_STREAM, );
memset(&serv_addr, '', sizeof(serv_addr));
memset(sendBuff, '', sizeof(sendBuff)); serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(); bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)); listen(listenfd, ); while()
{
connfd = accept(listenfd, (struct sockaddr*)NULL, NULL); ticks = time(NULL);
snprintf(sendBuff, sizeof(sendBuff), "%.24s\r\n", ctime(&ticks));
write(connfd, sendBuff, strlen(sendBuff)); close(connfd);
sleep();
}
}

In the above program, we have created a server. In the code :

  • The call to the function ‘socket()’ creates an UN-named socket inside the kernel and returns an integer known as socket descriptor.
  • This function takes domain/family as its first argument. For Internet family of IPv4 addresses we use AF_INET.
  • The second argument ‘SOCK_STREAM’ specifies that the transport layer protocol that we want should be reliable ie it should have acknowledgement techniques. For example : TCP
  • The third argument is generally left zero to let the kernel decide the default protocol to use for this connection. For connection oriented reliable connections, the default protocol used is TCP.
  • The call to the function ‘bind()’ assigns the details specified in the structure ‘serv_addr’ to the socket created in the step above. The details include, the family/domain, the interface to listen on(in case the system has multiple interfaces to network) and the port on which the server will wait for the client requests to come.
  • The call to the function ‘listen()’ with second argument as ’10′ specifies maximum number of client connections that server will queue for this listening socket.
  • After the call to listen(), this socket becomes a fully functional listening socket.
  • In the call to accept(), the server is put to sleep and when for an incoming client request, the three way TCP handshake* is complete, the function accept () wakes up and returns the socket descriptor representing the client socket.
  • The call to accept() is run in an infinite loop so that the server is always running and the delay or sleep of 1 sec ensures that this server does not eat up all of your CPU processing.
  • As soon as server gets a request from client, it prepares the date and time and writes on the client socket through the descriptor returned by accept().

Three way handshake is the procedure that is followed to establish a TCP connection between two remote hosts. We might soon be posting an article on the theoretical aspect of the TCP protocol.

Finally, we compile the code and run the server.

Socket Client Example

#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h> int main(int argc, char *argv[])
{
int sockfd = , n = ;
char recvBuff[];
struct sockaddr_in serv_addr; if(argc != )
{
printf("\n Usage: %s <ip of server> \n",argv[]);
return ;
} memset(recvBuff, '',sizeof(recvBuff));
if((sockfd = socket(AF_INET, SOCK_STREAM, )) < )
{
printf("\n Error : Could not create socket \n");
return ;
} memset(&serv_addr, '', sizeof(serv_addr)); serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(); if(inet_pton(AF_INET, argv[], &serv_addr.sin_addr)<=)
{
printf("\n inet_pton error occured\n");
return ;
} if( connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < )
{
printf("\n Error : Connect Failed \n");
return ;
} while ( (n = read(sockfd, recvBuff, sizeof(recvBuff)-)) > )
{
recvBuff[n] = ;
if(fputs(recvBuff, stdout) == EOF)
{
printf("\n Error : Fputs error\n");
}
} if(n < )
{
printf("\n Read error \n");
} return ;
}

In the above program, we create a client which will connect to the server and receive date and time from it. In the above piece of code :

  • We see that here also, a socket is created through call to socket() function.
  • Information like IP address of the remote host and its port is bundled up in a structure and a call to function connect() is made which tries to connect this socket with the socket (IP address and port) of the remote host.
  • Note that here we have not bind our client socket on a particular port as client generally use port assigned by kernel as client can have its socket associated with any port but In case of server it has to be a well known socket, so known servers bind to a specific port like HTTP server runs on port 80 etc while there is no such restrictions on clients.
  • Once the sockets are connected, the server sends the data (date+time) on clients socket through clients socket descriptor and client can read it through normal read call on the its socket descriptor.

Now execute the client as shown below.

$ ./newsc 127.0.0.1
Sun Dec ::

We can see that we successfully got the date and time from server. We need to send the IP address of the server as an argument for this example to run. If you are running both server and client example on the same machine for testing purpose, use the loop back ip address as shown above.

To conclude, In this article we studied the basics of socket programming through a live example that demonstrated communication between a client and server processes capable of running on two different machines.

C Socket Programming for Linux with a Server and Client Example Code的更多相关文章

  1. C++ socket programming in Linux

    Server.c #include <arpa/inet.h> #include <errno.h> #include <netinet/in.h> #includ ...

  2. 【Socket计划】使用C++实现Server结束Client结束

    我是在Visual Stdio 2013两人的建立project.编译如下两个人main文件,然后测试 服务器:Server.cpp #include <WINSOCK2.H> #incl ...

  3. TCP Socket Programming in Node.js

    TCP Socket Programming in Node.js Posted on October 26th, 2011 under Node.jsTags: Client, node.js, S ...

  4. Socket programming in C on Linux | tutorial

    TCP/IP socket programming This is a quick guide/tutorial to learning socket programming in C languag ...

  5. linux c socket programming

    原文:linux c socket programming http://54min.com/post/http-client-examples-using-c.html 好文章 PPT http:/ ...

  6. Socket Programming in C#--Server Side

    Server Side If you have understood whatever I have described so far, you will easily understand the ...

  7. [PHP-Socket] Socket Programming in PHP

    Simple Client-Server socket program in PHP Introduction Sockets are used for interprocess communicat ...

  8. Socket Programming in C#--Conclusion

    Conclusion And that's all there is to it! Here is how our client looks like Here is how our server l ...

  9. Socket Programming in C#--Getting Started

    Getting Started You can argue that one can overcome these shortcomings by multithreading meaning tha ...

随机推荐

  1. MYSQL-给带特殊符号的数据库创建用户名

    MYSQL-创建数据库及用户名: mysql> create database yoon;Query OK, 1 row affected (0.00 sec) mysql> grant ...

  2. myeclipse配置下tomcat debug启动很无比慢

    myeclipse配置下tomcat debug启动很无比慢,而run启动很快今天照常使用MyEclipse 6.5 Blue Edition进行开发,但是却遇到一个怪问题.在MyEclipse环境下 ...

  3. 在MAC平台下编译Ngnix ,由于MD5算法不能编译通过 解决办法

    近期想学习Ngnix 代码,前些日子,对”自己下手狠一次“, 买了MAC 本. 所以想在Mac 上编译,是必须的,不然对不起自己的内心. 不巧遇到了MD5算法编译的问题 src/core/ngx_cr ...

  4. cookie、session的联系和区别,多台web服务器如何共享session?

    cookie在客户端保存状态,session在服务器端保存状态.但是由于在服务器端保存状态的时候,在客户端也需要一个标识,所以session也可能要借助cookie来实现保存标识位的作用.cookie ...

  5. 【BZOJ 2245】[SDOI2011]工作安排

    Description 你的公司接到了一批订单.订单要求你的公司提供n类产品,产品被编号为1~n,其中第i类产品共需要Ci件.公司共有m名员工,员工被编号为1~m员工能够制造的产品种类有所区别.一件产 ...

  6. [分享] Code::Blocks Windows Console 中文亂碼解決

    相信各位大大們應該都有聽過Code::Blocks這個IDE,但網路上有許多人反應Code::Blocks不能編出中文的Console程式,但 Code::Blocks最新的版本預設使用UTF-8做為 ...

  7. C#加密NodeJS解密

    C#代码: class Program { static void Main(string[] args) { Console.WriteLine(", "abcdefghijkl ...

  8. c# 重载运算符(+-|&)和扩展方法

    通常我们需要对class的相加,相减,相乘 等重载以适应需求, 如caml查询的时候,我们可以定义一个caml类,然后来操作这些查询. 首先,我们定义一个class为Test public class ...

  9. Android开发在使用第三方推送的时候出现INSTALL_FAILED_VERSION_DOWNGRADE

    [-- :: - push_getui_test] Uploading push_getui_test.apk onto device 'emulator-5554' [-- :: - push_ge ...

  10. Android 开发 res里面的drawable(ldpi、mdpi、hdpi、xhdpi、xxhdpi)

    (1)drawable-hdpi里面存放高分辨率的图片,如WVGA (480x800),FWVGA (480x854) (2)drawable-mdpi里面存放中等分辨率的图片,如HVGA (320x ...