GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing www.tutorialspoint.com — C++ Socket Programming
Selected Reading
C++ Socket ProgrammingC++ socket programming is the way to establish communication between two sockets on the network using C++. In this tutorial, we will learn all about socket programming using different types of sockets in C++. What are Sockets?Sockets act as the contact points for network data exchange, it's like endpoints for sending and receiving data across a network. They allow applications to communicate with one another using protocols such as TCP (Transmission Control Protocol) and UDP (User Datagram Protocol). They are the backbone of most internet communication as it enables us from web browsing to real-time chatting. There are two types of sockets:
Socket Programming in C++Socket programming in C++ is a powerful approach to creating network applications that allow communication between devices over a network using the socket API. This process involves establishing connections between a client and a server, which enables data exchange through protocols like TCP or UDP. C++ Server-Side Socket (Listening for Connections)The following methods are used for handling server-side communication: 1. socket()The socket() is a system call in network programming that creates a new TCP socket in C++ that is defined inside the <sys/socket.h> header file. Syntaxint sockfd = socket(AF_INET, SOCK_STREAM, 0); Where,
2. bind()The bind() method is associated with a socket, with a specific local address and port number which allows the socket to listen for incoming connection on that address. Syntaxbind(sockfd, (struct sockaddr*)&address, sizeof(address)); Where,
3. listen()The listen() function marks the socket as a passive socket which prepares a socket to accept incoming connection requests (for servers). Syntaxlisten(sockfd, 10); Where,
4. accept()The accept() function accepts a new connection from a client (for servers). It extracts the first connection request on the queue of pending connections and creates a new socket for that connection. Syntaxint clientSocket = accept(sockfd, (struct sockaddr*)&clientAddress, &clientLen); Where,
C++ Client-Side Socket (Connecting to a Server)The following methods are used for client-side communication: 1. connect()This function is a system call that attempts to establish a connection to a specified server (for clients) using the socket. Syntaxconnect(sockfd, (struct sockaddr*)&serverAddress, sizeof(serverAddress)); Where,
2. send()The send() function is a system call in socket programming which sends data to a connected socket. Syntaxsend(sockfd, "Hello", strlen("Hello"), 0);
Where,
3. recv()The recv() function is a system call that is used to receive data from a connected socket which allows the client or server to read incoming messages. Syntaxrecv(sockfd, buffer, sizeof(buffer), 0); Where,
Closing the Client SocketThe close() method closes an open socket. Syntaxclose(sockfd); Where,
Required Header Files for Socket ProgrammingWhen programming with sockets in C or C++, specific header files must be included for the necessary declarations. For Linux/Unix Systems
For Windows Systems
C++ Example of Socket ProgrammingHere's a simple Example to illustrate a TCP server and client in C++: TCP Server Code#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include <cstring>
#include <iostream>
#define PORT 8080
int main() {
int server_fd, new_socket;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[1024] = {0};
// Create socket
server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// Attach socket to the port
setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
// Bind
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// Listen
if (listen(server_fd, 3) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
// Accept a connection
new_socket =
accept(server_fd, (struct sockaddr *)&address, (socklen_t *)&addrlen);
if (new_socket < 0) {
perror("accept");
exit(EXIT_FAILURE);
}
// Read data
read(new_socket, buffer, 1024);
std::cout << "Message from client: " << buffer << std::endl;
// Close socket
close(new_socket);
close(server_fd);
return 0;
}
TCP Client Code#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include <cstring>
#include <iostream>
#define PORT 8080
int main() {
int sock = 0;
struct sockaddr_in serv_addr;
const char *hello = "Hello from client";
// Create socket
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
std::cerr << "Socket creation error" << std::endl;
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
// Convert IPv4 and IPv6 addresses from text to binary
if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) {
std::cerr << "Invalid address/ Address not supported" << std::endl;
return -1;
}
// Connect to server
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
std::cerr << "Connection Failed" << std::endl;
return -1;
}
// Send data
send(sock, hello, strlen(hello), 0);
std::cout << "Message sent" << std::endl;
// Close socket
close(sock);
return 0;
}
Steps to Compile and RunThe following are the steps to compiler and run client socket program: To compiler both server and client code files: g++ -o server server.cpp g++ -o client client.cpp To run the Server: ./server To run the Client (in another terminal): ./client Best Practices
Real-world ApplicationsThere are various applications of sockets in real-life uses and tools etc, here’s mentioned a few of them. These examples demonstrate how to use sockets for different applications:
Advertisements
|
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |