85 lines
2.2 KiB
C
85 lines
2.2 KiB
C
|
#include <arpa/inet.h>
|
||
|
#include <stdio.h>
|
||
|
#include <stdlib.h>
|
||
|
#include <string.h>
|
||
|
#include <sys/socket.h>
|
||
|
#include <sys/types.h>
|
||
|
#include <unistd.h>
|
||
|
|
||
|
void handle_arguments(int argc, char *argv[]) {
|
||
|
if (argc != 2) {
|
||
|
fprintf(stderr, "Usage: %s PORT\n", argv[0]);
|
||
|
exit(EXIT_FAILURE);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
void send_integers(int sockfd, struct sockaddr_in * server_addr) {
|
||
|
int buffer = 42;
|
||
|
|
||
|
while (1) {
|
||
|
// int rv = sendto(sockfd, buffer.array, sizeof(buffer), 0, (const struct sockaddr *)&server_addr, sizeof(server_addr));
|
||
|
int rv = sendto(sockfd, &buffer, sizeof(buffer), 0, (const struct sockaddr *)&server_addr, sizeof(server_addr));
|
||
|
if (rv == -1) {
|
||
|
perror("sendto: ");
|
||
|
exit(EXIT_FAILURE);
|
||
|
}
|
||
|
// printf("Sent %x to the server\n", buffer.number);
|
||
|
sleep(10);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
void run_client(int port) {
|
||
|
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
|
||
|
if (sockfd < 0) {
|
||
|
fprintf(stderr, "socket: ");
|
||
|
exit(EXIT_FAILURE);
|
||
|
}
|
||
|
|
||
|
struct sockaddr_in server_addr;
|
||
|
memset(&server_addr, 0, sizeof(server_addr));
|
||
|
server_addr.sin_family = AF_INET;
|
||
|
server_addr.sin_addr.s_addr = INADDR_ANY;
|
||
|
server_addr.sin_port = htons(port);
|
||
|
if (connect(sockfd, (const struct sockaddr *)&server_addr, sizeof(server_addr))) {
|
||
|
perror("connect");
|
||
|
exit(EXIT_FAILURE);
|
||
|
}
|
||
|
|
||
|
pid_t pid;
|
||
|
pid = fork();
|
||
|
if (pid == -1) {
|
||
|
perror("fork: ");
|
||
|
exit(EXIT_FAILURE);
|
||
|
}
|
||
|
if (pid == 0) {
|
||
|
send_integers(sockfd, &server_addr);
|
||
|
}
|
||
|
|
||
|
char response[] = "DATA RECEIVED";
|
||
|
char buffer[100];
|
||
|
|
||
|
int rv;
|
||
|
while (1) {
|
||
|
rv = recv(sockfd, buffer, sizeof(buffer), 0);
|
||
|
if (rv < 0) {
|
||
|
fprintf(stderr, "recvfrom: ");
|
||
|
exit(EXIT_FAILURE);
|
||
|
}
|
||
|
if (strlen(buffer)) {
|
||
|
printf("From server: %s\n", buffer);
|
||
|
rv = send(sockfd, response, sizeof(response), 0);
|
||
|
if (rv == -1) {
|
||
|
perror("send");
|
||
|
exit(EXIT_FAILURE);
|
||
|
}
|
||
|
}
|
||
|
memset(&buffer, 0, sizeof(buffer));
|
||
|
}
|
||
|
}
|
||
|
|
||
|
int main(int argc, char *argv[]) {
|
||
|
handle_arguments(argc, argv);
|
||
|
run_client(strtol(argv[1], NULL, 10));
|
||
|
|
||
|
return 0;
|
||
|
}
|