Upon completion of this short, you will be able to:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#define PORT 2023
int main(int argc, char *argv[]) {
int sock;
struct sockaddr_in server;
char message[1000], server_reply[2000], file_contents[10000];
FILE *fp;
if (argc != 2) {
printf("Usage: %s <file name>\n", argv[0]);
return 1;
}
// Open the file
fp = fopen(argv[1], "r");
if (fp == NULL) {
perror("Error opening file");
return 1;
}
// Read file contents
fread(file_contents, sizeof(char), sizeof(file_contents), fp);
fclose(fp);
// Create socket
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
printf("Could not create socket");
}
// Prepare the sockaddr_in structure
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_family = AF_INET;
server.sin_port = htons(PORT);
// Connect to remote server
if (connect(sock, (struct sockaddr *)&server, sizeof(server)) < 0) {
perror("connect failed. Error");
return 1;
}
printf("Connected\n");
// Send file contents to the server
if (send(sock, file_contents, strlen(file_contents), 0) < 0) {
printf("send failed");
return 1;
}
// Receive message from the server
if (recv(sock, server_reply, 2000, 0) < 0) {
printf("recv failed");
return 1;
}
printf("Server reply: %s\n", server_reply);
close(sock);
return 0;
}None collected yet. Let us know.