Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
1.4 kB
1
Indexable
Never
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define PORT 1289
#define SERVER_IP "127.0.0.1"

int main() {
    int client_socket;
    struct sockaddr_in server_address;
    char buffer[1024];

    if ((client_socket = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        perror("Socket creation error");
        exit(EXIT_FAILURE);
    }

    memset(&server_address, '0', sizeof(server_address));
    server_address.sin_family = AF_INET;
    server_address.sin_port = htons(PORT);

    if (inet_pton(AF_INET, SERVER_IP, &server_address.sin_addr) <= 0) {
        perror("Invalid address / Address not supported");
        exit(EXIT_FAILURE);
    }

    if (connect(client_socket, (struct sockaddr *)&server_address, sizeof(server_address)) < 0) {
        perror("Connection failed");
        exit(EXIT_FAILURE);
    }

    while (1) {
        int message;
        printf("Enter the number: ");
        scanf("%d", &message);
        
        send(client_socket, &message, sizeof(int), 0);
        printf("Message sent\n");

        int valread = read(client_socket, buffer, 1024);
        if (valread <= 0) {
            printf("Server disconnected\n");
            break;
        }
        printf("Server response: %s\n", buffer);
    }

    close(client_socket);
    return 0;
}
Leave a Comment