client
user_1944374
c_cpp
2 years ago
1.7 kB
1
Indexable
Never
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <arpa/inet.h> #include <unistd.h> #define BUFFER_SIZE 1024 int main() { //accept the server port number and IP address from clients end char ip_address[INET_ADDRSTRLEN]; printf("Enter the server IP address: "); scanf("%s", ip_address); int port; printf("Enter the server port number: "); scanf("%d", &port); getchar(); int client_fd = socket(AF_INET, SOCK_STREAM, 0); if (client_fd < 0) { perror("socket() failed"); exit(1); } struct sockaddr_in server_addr = {0}; server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = inet_addr(ip_address); server_addr.sin_port = htons(port); //client connects to the server if (connect(client_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) { perror("connect() failed"); exit(1); } printf("Connected to server %s:%d\n", inet_ntoa(server_addr.sin_addr), ntohs(server_addr.sin_port)); while (1) { //client reads a string from the terminal and sends it to the server char message[BUFFER_SIZE] = {0}; printf("Enter a message (or 'quit' to exit): "); fgets(message, BUFFER_SIZE, stdin); if (send(client_fd, message, strlen(message), 0) < 0) { perror("send() failed"); break; } //communication continues till user types quit at clients end if (strcmp(message, "quit\n") == 0) { break; } } close(client_fd); return 0; }