Skip to content

Instantly share code, notes, and snippets.

@MarcusXavierr
Created January 5, 2025 01:39
Show Gist options
  • Save MarcusXavierr/51d68007c81897acd284f4f0dae1f321 to your computer and use it in GitHub Desktop.
Save MarcusXavierr/51d68007c81897acd284f4f0dae1f321 to your computer and use it in GitHub Desktop.
Um simples client TCP
#include <signal.h>
#include <string.h>
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <stdlib.h>
#include <unistd.h>
#define MAX_LINE 1024
int open_clientfd(char *hostname, char *port) {
int clientfd, rc;
struct addrinfo hints, *listp, *p;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_NUMERICSERV;
hints.ai_flags |= AI_ADDRCONFIG;
if ((rc = getaddrinfo(hostname, port, &hints, &listp)) != 0) {
fprintf(stderr, "Error connecting to server: %s\n", gai_strerror(rc));
exit(1);
}
for (p = listp; p; p = p->ai_next) {
if ((clientfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) < 0) {
continue;
}
if (connect(clientfd, p->ai_addr, p->ai_addrlen) != -1) {
break; // The connection was successful, and we break
}
close(clientfd);
}
freeaddrinfo(listp);
if (!p) { // None of the connections was successful
return -1;
} else {
return clientfd;
}
}
int main(int argc, char **argv) {
if (argc < 3) {
printf("Usage: %s <host> <port>", argv[0]);
}
int clientfd = open_clientfd(argv[1], argv[2]);
if (clientfd == -1) {
puts("Unable to connect to server");
exit(1);
}
char res[MAX_LINE];
char input[MAX_LINE] = "oi";
pid_t pid;
int input_pos = 0;
if ((pid = fork()) == 0) { // child process
while(1) {
if (read(clientfd, res, MAX_LINE) <= 0 ) {
puts("Server disconnected");
kill(-pid, SIGINT);
};
printf("\n");
printf("guest> %s", res);
memset(res, 0, MAX_LINE);
}
} else {
while(1) {
fgets(input, MAX_LINE, stdin);
printf("\033[A\r\033[K"); // clears the input so we can print the message below
printf("you> %s", input);
write(clientfd, input, strlen(input));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment