Untitled

mail@pastecode.io avatar
unknown
c_cpp
a month ago
1.2 kB
0
Indexable
Never
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <time.h>

int main() {
    int sd, nsd, clilen, sport;
    time_t ticks;
    char sendmsg[100];
    struct sockaddr_in servaddr, cliaddr;

    printf("Enter the server Port: ");
    scanf("%d", &sport);
    printf("%d\n", sport);

    sd = socket(AF_INET, SOCK_STREAM, 0);
    // socket creation
    if (sd < 0)
        printf("Can't create\n");
    else
        printf("Socket is created\n");

    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(sport);
    // the user
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    // search the client in the same machine

    if (bind(sd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
        printf("Can't bind\n");
        return -1;
    } else {
        printf("Binded\n");
    }

    listen(sd, 5);
    clilen = sizeof(cliaddr);
    nsd = accept(sd, (struct sockaddr *)&cliaddr, &clilen);
    if (nsd < 0)
        printf("Can't accept \n");
    else
        printf("Accepted \n");

    ticks = time(NULL);
    strcpy(sendmsg, ctime(&ticks));
    send(nsd, sendmsg, 100, 0);

    return 0;
}
Leave a Comment