- Setting Up Sockets To create a socket in C++, we need to include the
<sys/socket.h>
header file. Then, we can create a socket using thesocket()
function.
1#include <sys/socket.h>
2
3 int sock = socket(AF_INET, SOCK_STREAM, 0);
- Creating Server and Client Applications To create a server application, we need to bind the socket to an IP address and port using the
bind()
function. Then, we can start listening for incoming connections using thelisten()
function. Finally, we can accept a connection using theaccept()
function.
1 #include <netinet/in.h>
2
3struct sockaddr_in server_addr;
4
server_addr.sin_family = AF_INET;
5 server_addr.sin_addr.s_addr = INADDR_ANY;
6 server_addr.sin_port = htons(8080);
7
8 bind(sock, (struct sockaddr *)&server_addr, sizeof(server_addr));
9 listen(sock, 5);
10
11struct sockaddr_in client_addr;
12socklen_t client_addr_len = sizeof(client_addr);
13
14 int new_sock = accept(sock, (struct sockaddr *)&client_addr, &client_addr_len);
To create a client application, we need to establish a connection to the server using the connect()
function.
1 struct sockaddr_in server_addr;
2 server_addr.sin_family = AF_INET;
3 server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
4 server_addr.sin_port = htons(8080);
5
6 connect(sock, (struct sockaddr *)&server_addr, sizeof(server_addr));
- Sending and Receiving Data To send data over the socket, we can use the
send()
function. To receive data, we can use therecv()
function.
1 char data[100] = "Hello, World!";
2 send(new_sock, data, sizeof(data), 0);
3
4 char buffer[100];
5 recv(new_sock, buffer, sizeof(buffer), 0);
- Closing Sockets After we are done with the socket, we need to close it using the
close()
function.
1 close(new_sock);
2 close(sock);
Please note that the above code snippets are just basic examples. In real-world applications, error handling, network protocols, and security measures are also essential.
About Author
Discover more from SURFCLOUD TECHNOLOGY
Subscribe to get the latest posts sent to your email.