Untitled
unknown
c_cpp
3 years ago
2.9 kB
11
Indexable
//client.c
int main() {
//Declare variables
int sock, num_bytes;
struct sockaddr_in servaddr;
char* buffer = malloc(1024*sizeof(char));
// Create socket
sock = socket(AF_INET, SOCK_STREAM, 0); // create a socket with the given domain, type and protocol
if (sock < 0) { // check if socket creation was unsuccessful
printf("Error creating socket\n"); // print an error message
return 1; // exit the program with an error code
}
// Fill in server address information
memset(&servaddr, 0, sizeof(servaddr)); // fill the memory with 0s
servaddr.sin_family = AF_INET; // set the address family to IPv4
servaddr.sin_port = htons(SERVER_PORT); // set the server port number
if (inet_pton(AF_INET, SERVER_ADDRESS, &servaddr.sin_addr) <= 0) { // convert the server address from text to binary
printf("Invalid address or address not supported\n"); // print an error message if the conversion fails
return 1; // exit the program with an error code
}
// Connect to server
if (connect(sock, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) { // Try to connect to the server
printf("Error connecting to server\n"); // If connection fails, print error message
return 1; // Return 1 to indicate an error has occurred
} else {
printf("\n************Connected to the server************\n"); // If connection succeeds, print success message
}
buffer = get_validated_input();
num_bytes = send(sock, buffer, 1024, 0); // Send input data to server
if (num_bytes < 0) {
printf("Error sending data to server\n"); // If sending data fails, print error message
return 1; // Return 1 to indicate an error has occurred
} else {
// Pass command and data to server
printf("\nSending Input Data: '%s' to the Server\n\n", buffer);
}
//Receiving data from the server
char output_string[1024];
int bytes = read(sock, output_string, 1024); // Receive data from server
if (bytes < 0) {
printf("Error receiving data from server\n"); // If receiving data fails, print error message
return 1; // Return 1 to indicate an error has occurred
}
output_string[bytes] = '\0'; // Add null terminator to the end of the string
printf("Received data: %s\n\n", output_string); // Print output data received from server
// Close socket
close(sock);
return 0;
}
Editor is loading...