#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <sys/time.h>
#include <arpa/inet.h>
#include <string.h>
#include <time.h>

int main() {
    int server_sockfd, client_sockfd;
    int server_len, client_len;
    char msg1[100];
    time_t t;
    struct sockaddr_in server_address, client_address;

    // Create a TCP socket
    server_sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (server_sockfd < 0) {
        perror("Error in socket creation");
        return 1;
    }

    // Initialize server address struct
    server_address.sin_family = AF_INET;
    server_address.sin_port = htons(4006); // Convert port to network byte order
    server_address.sin_addr.s_addr = htonl(INADDR_ANY);

    server_len = sizeof(server_address);

    // Bind the socket to the server address
    if (bind(server_sockfd, (struct sockaddr *)&server_address, server_len) < 0) {
        perror("Error in binding");
        return 1;
    }

    // Listen for incoming connections
    listen(server_sockfd, 5);

    client_len = sizeof(client_address);

    // Accept a connection from a client
    client_sockfd = accept(server_sockfd, (struct sockaddr *)&client_address, &client_len);
    if (client_sockfd < 0) {
        perror("Error in accepting connection");
        return 1;
    }

    // Get current time
    t = time(NULL);
    sprintf(msg1, "%s", ctime(&t));
    
    // Send time to client
    write(client_sockfd, msg1, strlen(msg1) + 1);

    // Close client socket
    close(client_sockfd);

    // Close server socket
    close(server_sockfd);

    return 0;
}



Client side 

#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>

int main() {
    int sockfd, len, result;
    struct sockaddr_in address;
    char msg1[100];

    // Create a TCP socket
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        perror("Error in socket creation");
        exit(1);
    }

    // Initialize server address struct
    address.sin_family = AF_INET;
    address.sin_port = htons(4006); // Convert port to network byte order
    address.sin_addr.s_addr = inet_addr("127.0.0.1");
    len = sizeof(address);

    // Connect to the server
    result = connect(sockfd, (struct sockaddr *)&address, len);
    if (result == -1) {
        perror("Error in connecting");
        exit(1);
    }

    // Read time from server
    read(sockfd, msg1, sizeof(msg1));

    // Print received time
    printf("Time received from server: %s\n", msg1);

    // Close socket
    close(sockfd);

    return 0;
}

Comments