chatc.c
2.12 KB
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include "chat.h"
#define MAX_BUF 256
int Sockfd;
void
ChatClient(void)
{
char buf[MAX_BUF];
int count, n;
fd_set fdset;
printf("Enter ID: ");
fflush(stdout);
fgets(buf, MAX_BUF, stdin);
*strchr(buf, '\n') = '\0';
if (send(Sockfd, buf, strlen(buf)+1, 0) < 0) {
perror("send");
exit(1);
}
printf("Press ^C to exit\n");
while (1) {
FD_ZERO(&fdset);
FD_SET(Sockfd, &fdset);
FD_SET(STDIN_FILENO, &fdset);
if ((count = select(10, &fdset, (fd_set *)NULL, (fd_set *)NULL,
(struct timeval *)NULL)) < 0) {
perror("select");
exit(1);
}
while (count--) {
if (FD_ISSET(Sockfd, &fdset)) {
if ((n = recv(Sockfd, buf, MAX_BUF, 0)) < 0) {
perror("recv");
exit(1);
}
if (n == 0) {
fprintf(stderr, "Server terminated.....\n");
close(Sockfd);
exit(1);
}
printf("%s", buf);
}
else if (FD_ISSET(STDIN_FILENO, &fdset)) {
fgets(buf, MAX_BUF, stdin);
if ((n = send(Sockfd, buf, strlen(buf)+1, 0)) < 0) {
perror("send");
exit(1);
}
}
}
}
}
void
CloseClient(int signo)
{
close(Sockfd);
printf("\nChat client terminated.....\n");
exit(0);
}
main(int argc, char *argv[])
{
struct sockaddr_in servAddr;
struct hostent *hp;
if (argc != 2) {
fprintf(stderr, "Usage: %s ServerIPaddress\n", argv[0]);
exit(1);
}
if ((Sockfd = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
perror("socket");
exit(1);
}
bzero((char *)&servAddr, sizeof(servAddr));
servAddr.sin_family = PF_INET;
servAddr.sin_port = htons(SERV_TCP_PORT);
if (isdigit(argv[1][0])) {
servAddr.sin_addr.s_addr = inet_addr(argv[1]);
}
else {
if ((hp = gethostbyname(argv[1])) == NULL) {
fprintf(stderr, "Unknown host: %s\n", argv[1]);
exit(1);
}
memcpy(&servAddr.sin_addr, hp->h_addr, hp->h_length);
}
if (connect(Sockfd, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0) {
perror("connect");
exit(1);
}
signal(SIGINT, CloseClient);
ChatClient();
}