Working with Sockets
To establish a network connection in C++, you can use sockets. Sockets are endpoints for network communication that allow you to send and receive data over a network.
Here's an example of how you can work with sockets to establish a basic network connection in C++:
TEXT/X-C++SRC
1#include <iostream>
2#include <sys/socket.h>
3#include <arpa/inet.h>
4#include <unistd.h>
5
6int main() {
7 // Create a socket
8 int sock = socket(AF_INET, SOCK_STREAM, 0);
9 if (sock == -1) {
10 std::cerr << "Failed to create socket" << std::endl;
11 return 1;
12 }
13
14 // Socket address structure
15 sockaddr_in address;
16 address.sin_family = AF_INET;
17 address.sin_port = htons(8080);
18 if (inet_pton(AF_INET, "127.0.0.1", &(address.sin_addr)) == -1) {
19 std::cerr << "Failed to set address" << std::endl;
20 return 1;
21 }
22
23 // Connect to the server
24 if (connect(sock, (struct sockaddr *)&address, sizeof(address)) == -1) {
25 std::cerr << "Failed to connect to server" << std::endl;
26 return 1;
27 }
28
29 // Send data
30 const char *message = "Hello, server!";
31 if (send(sock, message, strlen(message), 0) == -1) {
32 std::cerr << "Failed to send data" << std::endl;
33 return 1;
34 }
35
36 // Receive data
37 char buffer[1024] = {0};
38 if (recv(sock, buffer, 1024, 0) == -1) {
39 std::cerr << "Failed to receive data" << std::endl;
40 return 1;
41 }
42 std::cout << "Server response: " << buffer << std::endl;
43
44 // Close the socket
45 close(sock);
46
47 return 0;
48}
xxxxxxxxxx
48
}
int main() {
// Create a socket
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
std::cerr << "Failed to create socket" << std::endl;
return 1;
}
// Socket address structure
sockaddr_in address;
address.sin_family = AF_INET;
address.sin_port = htons(8080);
if (inet_pton(AF_INET, "127.0.0.1", &(address.sin_addr)) == -1) {
std::cerr << "Failed to set address" << std::endl;
return 1;
}
// Connect to the server
if (connect(sock, (struct sockaddr *)&address, sizeof(address)) == -1) {
std::cerr << "Failed to connect to server" << std::endl;
return 1;
}
// Send data
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment