Untitled

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

#define SERVER_PORT 1096
#define SERVER_IP_ADDRESS "127.0.0.1"

/* 
  Napisz programy, które będą realizował polecenie zawarte w zadaniu pierwszym, ale w oparciu
  o protokół TCP/IP. 
*/

void send_message(int socket_descriptor, struct sockaddr_in server_address, struct in_addr network_address)
{
  char buffer[512];
  if (!inet_aton(SERVER_IP_ADDRESS, &network_address))
    perror("inet_aton");

  const char *message = "Komunikat przesłany przez sieć.";
  if (sendto(socket_descriptor, message, strlen(message), 0, (struct sockaddr *)&server_address, sizeof(server_address)) < 0)
    perror("sendto");

  socklen_t address_length = sizeof(server_address);
  int received_bytes = recvfrom(socket_descriptor, (void *)buffer, sizeof(buffer), 0, (struct sockaddr *)&server_address, &address_length);
  if (received_bytes < 0)
    perror("recvfrom");
  else
  {
    buffer[received_bytes] = '\0';
    puts(buffer);
  }
}

int main(void)
{
  struct in_addr network_address;

  struct sockaddr_in server_address = {
      .sin_family = AF_INET,
      .sin_port = SERVER_PORT,
      .sin_addr = network_address};

  int socket_descriptor = socket(AF_INET, SOCK_STREAM, 0);
  if (socket_descriptor < 0)
    perror("socket");

  if (connect(socket_descriptor, (struct sockaddr *)&server_address, sizeof(struct sockaddr)) == -1)
  {
    puts("Nieudana próba połączenia.");
    perror("connect: ");
    return -1;
  }
  else
  {
    puts("Nawiązano połączenie.");
  }

  send_message(socket_descriptor, server_address, network_address);

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