Example of Socket Programming in C++
server.cpp
C++
// C++ program to show the example of server application in // socket programming #include <cstring> #include <iostream> #include <netinet/in.h> #include <sys/socket.h> #include <unistd.h> using namespace std; int main() { // creating socket int serverSocket = socket(AF_INET, SOCK_STREAM, 0); // specifying the address sockaddr_in serverAddress; serverAddress.sin_family = AF_INET; serverAddress.sin_port = htons(8080); serverAddress.sin_addr.s_addr = INADDR_ANY; // binding socket. bind(serverSocket, ( struct sockaddr*)&serverAddress, sizeof (serverAddress)); // listening to the assigned socket listen(serverSocket, 5); // accepting connection request int clientSocket = accept(serverSocket, nullptr, nullptr); // recieving data char buffer[1024] = { 0 }; recv(clientSocket, buffer, sizeof (buffer), 0); cout << "Message from client: " << buffer << endl; // closing the socket. close(serverSocket); return 0; } |
client.cpp
C++
// C++ program to illustrate the client application in the // socket programming #include <cstring> #include <iostream> #include <netinet/in.h> #include <sys/socket.h> #include <unistd.h> int main() { // creating socket int clientSocket = socket(AF_INET, SOCK_STREAM, 0); // specifying address sockaddr_in serverAddress; serverAddress.sin_family = AF_INET; serverAddress.sin_port = htons(8080); serverAddress.sin_addr.s_addr = INADDR_ANY; // sending connection request connect(clientSocket, ( struct sockaddr*)&serverAddress, sizeof (serverAddress)); // sending data const char * message = "Hello, server!" ; send(clientSocket, message, strlen (message), 0); // closing socket close(clientSocket); return 0; } |
By compiling and running server and client source files, we get the following output.
Output
As we can see, the message we sent to the server at port 8080 is revived and printed by the server. We can also create a loop where we can keep sending the messages to the server.
Socket Programming in C++
In C++, socket programming refers to the method of communication between two sockets on the network using a C++ program. We use the socket API to create a connection between the two programs running on the network, one of which receives the data by listening to the particular address port, and the other sends the data. One of the features of the socket programming is that it allows the bidirectional communication between the nodes.
In this article, we will create some simple C++ programs to demonstrate the use of socket programming.
Contact Us