Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
2.0 kB
1
Indexable
Never
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/ip.h>

#define PORT 1096

void name_socket(int socket_descriptor)
{
  struct sockaddr_in server_address = {
      .sin_family = AF_INET,
      .sin_port = PORT,
      .sin_addr = {INADDR_ANY}};

  if (bind(socket_descriptor, (struct sockaddr *)&server_address, sizeof(server_address)) < 0)
    perror("bind");
}

void get_and_print_message(int socket_descriptor)
{
  char buffer[512];
  struct sockaddr_in client_address;
  socklen_t address_length = sizeof(client_address);

  int received_bytes = recvfrom(socket_descriptor, (void *)buffer, sizeof(buffer), 0, (struct sockaddr *)&client_address, &address_length);
  if (received_bytes < 0)
    perror("recvfrom");
  else
  {
    buffer[received_bytes] = '\0';
    puts(buffer);
    const char *message = "Serwer odebrał komunikat.";
    if (sendto(socket_descriptor, message, strlen(message), 0, (struct sockaddr *)&client_address, sizeof(client_address)) < 0)
      perror("sendto");
  }
}

int main(void)
{
  socklen_t _size;
  struct sockaddr_in sender_addr;
  int socket_descriptor = socket(AF_INET, SOCK_STREAM, 0);
  if (socket_descriptor < 0)
    perror("socket");

  name_socket(socket_descriptor);

  if (listen(socket_descriptor, SOMAXCONN) == -1)
  {
    puts("Nie udało się nasłuchiwać.");
    close(socket_descriptor);
    perror("listen: ");
    return -1;
  }
  puts("Oczekuję na połączenie...");

  _size = sizeof(struct sockaddr);
  int accept_socket = accept(socket_descriptor, (struct sockaddr *)&sender_addr, &_size);
  if (accept_socket == -1)
  {
    puts("Nieudana próba przy połączeniu.");
    close(socket_descriptor);
    close(accept_socket);
    perror("accept: ");
    return -1;
  }

  get_and_print_message(accept_socket);

  if (close(socket_descriptor) < 0 || close(accept_socket) < 0)
    perror("close");
  return 0;
}