-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.cpp
More file actions
51 lines (41 loc) · 1.71 KB
/
Copy pathclient.cpp
File metadata and controls
51 lines (41 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <iostream>
#include <cstring>
#include <cerrno>
//Socket Headers
#include <arpa/inet.h> // For int to network byte order
#include <sys/socket.h> // For socket() methods
#include <netinet/in.h> // For sockaddr_in structure
#include <unistd.h> // For closing the socket
//Helper function similar to server.cpp
static void die(const char* msg) {
std::cerr << msg << ": " << std::strerror(errno) << std::endl;
std::exit(1);
}
int main() {
/* 1. Create a socket descriptor
This socket is not bound by any specific port, OS will assign a random port */
int sock_fd = socket(AF_INET, SOCK_STREAM, 0);
if(sock_fd == -1) die("Socket");
/* 2. Connect to the server with a specific IP address and port
Hardcode the server address and port for now */
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8080);
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
/* 3. Connect to the server
If the server is running, then this will complete the 3-way handshake and the connection is established */
if(connect(sock_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) die("Connect");
/* 4. Send data to the server */
const char* msg = "Hello Server, from the Client!";
ssize_t bytes_sent = send(sock_fd, msg, strlen(msg), 0);
if(bytes_sent == -1) die("Send");
/* 5. Receive data from the server */
char buffer[4096];
ssize_t bytes_received = recv(sock_fd, buffer, sizeof(buffer) - 1, 0);
if(bytes_received == -1) die("recv");
buffer[bytes_received] = '\0';
std::cout << "Received from server: " << buffer << std::endl;
/* 6. Close the socket */
close(sock_fd);
return 0;
}