|
@@ -0,0 +1,70 @@
|
|
|
|
|
+#include <stdio.h>
|
|
|
|
|
+#include <stdlib.h>
|
|
|
|
|
+#include <string.h>
|
|
|
|
|
+#include <unistd.h>
|
|
|
|
|
+#include <sys/types.h>
|
|
|
|
|
+#include <sys/socket.h>
|
|
|
|
|
+#include <netinet/in.h>
|
|
|
|
|
+#include <arpa/inet.h>
|
|
|
|
|
+
|
|
|
|
|
+#include "Practical.h"
|
|
|
|
|
+
|
|
|
|
|
+int main(int argc, char **argv) {
|
|
|
|
|
+ if (argc < 3 || argc > 4) {
|
|
|
|
|
+ DieWithUserMessage("Parameter(s)", "<Server Address> <Echo Word> [<Server Port>]");
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ const char *server_ip = argv[1];
|
|
|
|
|
+ const char *echo_str = argv[2];
|
|
|
|
|
+ const in_port_t server_port = (argc == 4) ? atoi(argv[3]) : 7; // 7: common echo port
|
|
|
|
|
+
|
|
|
|
|
+ const int sock = socket(AF_INET, SOCK_STREAM, proto_get_num("tcp"));
|
|
|
|
|
+ if (sock < 0) {
|
|
|
|
|
+ DieWithSystemMessage("socket() failed");
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ struct sockaddr_in server_addr = {0};
|
|
|
|
|
+ server_addr.sin_family = AF_INET;
|
|
|
|
|
+ int ret_val = inet_pton(AF_INET, server_ip, &server_addr.sin_addr.s_addr);
|
|
|
|
|
+ if (ret_val == 0) {
|
|
|
|
|
+ DieWithUserMessage("inet_pton() failed", "invalid address string");
|
|
|
|
|
+ } else if (ret_val < 0) {
|
|
|
|
|
+ DieWithSystemMessage("inet_pton() failed");
|
|
|
|
|
+ }
|
|
|
|
|
+ server_addr.sin_port = htons(server_port);
|
|
|
|
|
+
|
|
|
|
|
+ if (connect(sock, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
|
|
|
|
|
+ DieWithSystemMessage("connect() failed");
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ const size_t echo_str_len = strlen(echo_str);
|
|
|
|
|
+
|
|
|
|
|
+ ssize_t num_bytes = send(sock, echo_str, echo_str_len, 0);
|
|
|
|
|
+ if (num_bytes < 0) {
|
|
|
|
|
+ DieWithSystemMessage("send() failed");
|
|
|
|
|
+ } else if ((size_t) num_bytes != echo_str_len) {
|
|
|
|
|
+ DieWithUserMessage("send()", "sent unexpected number of bytes");
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ unsigned int total_bytes_rcvd = 0;
|
|
|
|
|
+ fputs("Received: ", stdout);
|
|
|
|
|
+ while (total_bytes_rcvd < echo_str_len) {
|
|
|
|
|
+ char buffer[BUFSIZE];
|
|
|
|
|
+ num_bytes = recv(sock, buffer, BUFSIZE - 1, 0);
|
|
|
|
|
+ if (num_bytes < 0) {
|
|
|
|
|
+ DieWithSystemMessage("recv() failed");
|
|
|
|
|
+ } else if (num_bytes == 0) {
|
|
|
|
|
+ DieWithUserMessage("recv()", "connection closed prematurely");
|
|
|
|
|
+ }
|
|
|
|
|
+ total_bytes_rcvd += num_bytes;
|
|
|
|
|
+ buffer[num_bytes] = '\0';
|
|
|
|
|
+ fputs(buffer, stdout);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ fputc('\n', stdout);
|
|
|
|
|
+
|
|
|
|
|
+ close(sock);
|
|
|
|
|
+
|
|
|
|
|
+ return 0;
|
|
|
|
|
+}
|
|
|
|
|
+
|