-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.c
98 lines (70 loc) · 1.7 KB
/
client.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
90
91
92
93
94
95
96
97
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<string.h>
#include<ctype.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
#include<errno.h>
#include<sys/ioctl.h>
#include<strings.h>
int main(int argc, char * argv[])
{
int sock;
struct sockaddr_in server;
struct hostent *hp;
char buf[1024];
/*Create socker*/
sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock < 0)
{
perror("socket creating");
exit(1);
}
/*connect socket using name specified by the command line*/
server.sin_family = AF_INET;
hp = gethostbyname(argv[1]);
if( hp == 0)
{
exit(2);
}
bcopy(hp -> h_addr, &server.sin_addr, hp->h_length);
server.sin_port = htons(atoi(argv[2]));
if(connect(sock, (struct sockaddr *) &server, sizeof(server)) < 0)
{
perror("connect to stream socket");
exit(0);
}
while(1)
{
char * writeBuff = (char *)malloc(100 * sizeof(char));
int readFromScreen = read(STDIN_FILENO, writeBuff,100);
write(sock , writeBuff, readFromScreen);
char readBuff;
int readFromSocket = 0;
int count = 0;
char readWriteBuff[100];
bzero(readWriteBuff,100);
int status;
do{
readFromSocket = read(sock,&readBuff,1);
if(readFromSocket == 0)
{
write(STDOUT_FILENO,"Connection ended\n",strlen("Connection ended\n"));
exit(EXIT_SUCCESS);
}
readWriteBuff[count] = readBuff;
count++;
ioctl(sock,FIONREAD, &status);
}while(status != 0);
write(STDOUT_FILENO, readWriteBuff,count);
if(strcmp("Connection terminated\n",readWriteBuff) == 0)
exit(0);
free(writeBuff);
}
close(sock);
}