JustPaste
HomeCategoriesAboutDonateContactTerms of UsePrivacy Policy
JustPaste

Free online notepad — write and share instantly

Navigate

  • Home
  • Timeline
  • Categories

Info

  • About
  • Donate
  • Contact

Legal

  • Terms of Use
  • Privacy Policy

© 2026 JustPaste.app. All rights reserved.

Made with ♥ by JustPaste

Untitled Page | JustPaste.app
16 days ago34 views
👨‍💻Programming

Server.c

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

#define SERVER_PORT 5432
#define MAX_PENDING 5
#define MAX_LINE 256

int main()
{
    struct sockaddr_in sin;
    char buf[MAX_LINE];
    int len, s, new_s;
    socklen_t addr_len;

    memset(&sin, 0, sizeof(sin));
    sin.sin_family = AF_INET;
    sin.sin_addr.s_addr = INADDR_ANY;
    sin.sin_port = htons(SERVER_PORT);

    if ((s = socket(PF_INET, SOCK_STREAM, 0)) < 0)
    {
        perror("Simplex-talk:socket");
        exit(1);
    }

    if ((bind(s, (struct sockaddr *)&sin, sizeof(sin))) < 0)
    {
        perror("Simplex-talk:bind");
        exit(1);
    }

    listen(s, MAX_PENDING);

    while (1)
    {
        addr_len = sizeof(sin);
        if ((new_s = accept(s, (struct sockaddr *)&sin, &addr_len)) < 0)
        {
            perror("Simplex-talk:accept");
            exit(1);
        }
        while ((len = recv(new_s, buf, sizeof(buf), 0)) > 0)
        {
            buf[len] = '\0';
            fputs(buf, stdout);
        }
        close(new_s);
    }

    return 0;
}



client.c

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

#define SERVER_PORT 5432
#define MAX_LINE 256

int main(int argc, char *argv[])
{
    struct sockaddr_in sin;
    struct hostent *hp;
    char buf[MAX_LINE];
    char *host;
    int len, s;

    if (argc == 2)
    {
        host = argv[1];
    }
    else
    {
        fprintf(stderr, "usage: simplex-talk host\n");
        exit(1);
    }

    hp = gethostbyname(host);
    if (!hp)
    {
        fprintf(stderr, "simplex-talk: unknown host: %s\n", host);
        exit(1);
    }

    memset(&sin, 0, sizeof(sin));
    sin.sin_family = AF_INET;
    memcpy(&sin.sin_addr, hp->h_addr, hp->h_length);
    sin.sin_port = htons(SERVER_PORT);

    if ((s = socket(PF_INET, SOCK_STREAM, 0)) < 0)
    {
        perror("Simplex-talk:socket");
        exit(1);
    }

    if ((connect(s, (struct sockaddr *)&sin, sizeof(sin))) < 0)
    {
        perror("Simplex-talk:connect");
        close(s);
        exit(1);
    }

    while (fgets(buf, sizeof(buf), stdin))
    {
        buf[MAX_LINE - 1] = '\0';
        len = strlen(buf) + 1;
        send(s, buf, len, 0);
    }

    close(s);
    return 0;
}
← Back to timeline