-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
89 lines (74 loc) · 2.09 KB
/
main.c
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
/**
* Developer : Nashid P
* Description : Simple TCP Socket Client in C
**/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <pthread.h>
#define MAX_SIZE 2048
void help_menu();
// thread function for listening
void *listen_sock(void *argp);
int sock;
struct sockaddr_in host;
int main(int argc, char *argv[]) {
int port;
pthread_t listen_thread;
char message[MAX_SIZE];
if(argc == 3) {
for(int i=1;i<argc;i++) {
if(argv[i][0] == '-' && argv[0][1] == 'h')
help_menu();
}
port = atoi(argv[2]);
sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock == -1) {
printf("Could not create socket");
}
host.sin_addr.s_addr = inet_addr(argv[1]);
host.sin_family = AF_INET;
host.sin_port = htons(port);
if(connect(sock, (struct sockaddr *)&host, sizeof(host)) < 0) {
perror("Failed to connect \n");
return 1;
}
printf("Connection Established \n");
// create thread for listening messages
pthread_create(&listen_thread, NULL, listen_sock, NULL);
while(1) {
fgets(message, MAX_SIZE, stdin);
// send data
if(send(sock, message, strlen(message), 0) < 0) {
printf("Failed to send message \n");
return 1;
}
}
close(sock);
} else {
help_menu();
}
pthread_exit(NULL);
return 0;
}
void help_menu() {
printf("Usage : netchat [IP] [PORT] \n");
}
void *listen_sock(void *argp) {
char reply[MAX_SIZE + 1];
while(1) {
// receive data
size_t r = recv(sock, reply, MAX_SIZE, 0);
if(r <= 0 || r > MAX_SIZE) {
fprintf(stderr, "Failed to recieve message \n");
exit(1);
} else {
// NULL terminate string ( clear buffer and prevent String Termination Error)
reply[r] = '\0';
printf("%s", reply);
}
}
}