summaryrefslogtreecommitdiff
path: root/client.c
blob: 9be43aea52e7309f0cf968daba78368eeedfe9bc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <unistd.h>
#include <stdbool.h>
#include <fcntl.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <signal.h>

#define __FAIL EXIT_FAILURE
#define BACKLOG 2
#define __PORT "62000"
#define BUF_SZ_2 2048

void talk_to_server (int sockfd) {
	
	while (1) {
        char editbuffer[BUF_SZ_2];
        fprintf(stdout, ": ");

        char *fgs = fgets(editbuffer, BUF_SZ_2, stdin);
		socklen_t fgs_len = strlen(editbuffer);
		if (fgs == NULL) {
			continue;
		}

        if (editbuffer[0] == '\n') { 
			send(sockfd, editbuffer, fgs_len, 0);
			continue;
		} else {
			send(sockfd, editbuffer, fgs_len, 0);
			continue;
		}
	}
}

void INThandler(int sockfd) {

	fprintf(stderr, "\n");
	close(sockfd);
	exit(0);
}

int main (int argc, char *argv[]) {

	if (argc != 2) {
		fprintf(stderr, "USAGE: %s [IP]\n", argv[0]);
		exit(__FAIL);
	}
	
	int sockfd = -1;
	int gai_result;
	int connect_result = -1;
	struct addrinfo hints;
	struct addrinfo *res;
	struct addrinfo *p;
	memset(&hints, 0, sizeof(hints));
	hints.ai_family = AF_INET;
	hints.ai_socktype = SOCK_STREAM;
	
	gai_result = getaddrinfo(argv[1], __PORT, &hints, &res);
	if (gai_result != 0) {
		fprintf(stderr, "getaddrinfo: %d\n", gai_result);
		exit(__FAIL);
	}

	for (p = res ; p != NULL ; p = p->ai_next) {

		sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
		if (sockfd == -1) {
			fprintf(stderr, "socket fail\n");
			continue;
		}
		
		connect_result = connect(sockfd, p->ai_addr, p->ai_addrlen);
		if (connect_result == -1) {
			fprintf(stderr, "connect fail\n");
			continue;
		}

	}
	if (connect_result == -1 || sockfd == -1) {
		close(sockfd);
		exit(__FAIL);
	}

	signal(SIGINT, INThandler);
	freeaddrinfo(res);
	talk_to_server(sockfd);
	
	return 0;
}