0% found this document useful (0 votes)
2 views

client program

This document is a C program that implements a simple TCP client. It connects to a server at localhost on port 12345, allowing the user to send messages and receive responses. The program handles socket creation, connection, message sending, and reading from the server, with error handling for various failure scenarios.

Uploaded by

Eshan Jinabade
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

client program

This document is a C program that implements a simple TCP client. It connects to a server at localhost on port 12345, allowing the user to send messages and receive responses. The program handles socket creation, connection, message sending, and reading from the server, with error handling for various failure scenarios.

Uploaded by

Eshan Jinabade
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <stdio.

h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define PORT 12345


#define BUFFER_SIZE 1024

int main() {
int client_fd;
struct sockaddr_in server_addr;
char buffer[BUFFER_SIZE];

if ((client_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {


perror("Socket creation failed");
exit(EXIT_FAILURE);
}

server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);

if (inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr) <= 0) {


perror("Invalid address/Address not supported");
close(client_fd);
exit(EXIT_FAILURE);
}

if (connect(client_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) <


0) {
perror("Connection failed");
close(client_fd);
exit(EXIT_FAILURE);
}

printf("Connected to server. Type messages to send:\n");

while (1) {
printf("You: ");
fgets(buffer, BUFFER_SIZE, stdin);

if (send(client_fd, buffer, strlen(buffer), 0) < 0) {


perror("Send failed");
break;
}

memset(buffer, 0, BUFFER_SIZE);
int bytes_read = read(client_fd, buffer, BUFFER_SIZE);
if (bytes_read <= 0) {
printf("Server disconnected.\n");
break;
}

printf("Server: %s", buffer);


}

close(client_fd);
return 0;
}

You might also like