-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.c
More file actions
80 lines (71 loc) · 1.99 KB
/
client.c
File metadata and controls
80 lines (71 loc) · 1.99 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
/*
* client.c
* ソケットを使用して、サーバーに接続するクライアントプログラム。
*
* 入力された文字列をサーバーに送り、サーバーが大文字に変換したデータを
* 受け取る。
*
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <netdb.h>
#define PORT 8765
main(int argc, char *argv[])
{
struct sockaddr_in addr;
struct hostent *hp;
int fd;
int len;
char buf[1024];
int ret;
if (argc != 2){
printf("Usage: iclient SERVER_NAME\n");
exit(1);
}
/*
* ストリーム型ソケット作る.
*/
/* if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { */
if ((fd = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
perror("socket");
exit(1);
}
/*
* addrの中身を0にしておかないと、bind()でエラーが起こることがある
*/
bzero((char *)&addr, sizeof(addr));
/*
* ソケットの名前を入れておく
*/
if ((hp = gethostbyname(argv[1])) == NULL) {
perror("No such host");
exit(1);
}
bcopy(hp->h_addr, &addr.sin_addr, hp->h_length);
/* addr.sin_family = AF_INET; */
addr.sin_family = PF_INET;
addr.sin_port = htons(PORT);
/*
* サーバーとの接続を試みる。これが成功するためには、サーバーがすでに
* このアドレスをbind()して、listen()を発行していなければならない。
*/
if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0){
perror("connect");
exit(1);
}
/*
* 入力されたデータをソケットに書き込んでサーバーに送り、
* サーバーが変換して送ってきたデータを読み込む。
*/
while (fgets(buf, 1024, stdin)) {
write(fd, buf, 1024);
ret = read(fd, buf, 1024);
buf[ret] = '\0';
/*write(1, buf, ret);*/
printf("%s",buf);
}
close(fd);
exit(0);
}