/*
* dclient.c
* ソケットを使用して、サーバーに接続するクライアントプログラム。
* DGRAM型のソケットを使う。
*
* 入力された文字列をサーバーに送り、サーバーが大文字に変換したデータを
* 受け取る。
*
*/
#include < stdio.h >
#include < string.h >
#include < sys/types.h >
#include < sys/socket.h >
#include < netinet/in.h >
#include < netdb.h >
#define PORT 8765
main(int argc, char *argv[])
{
struct sockaddr_in saddr;
struct hostent *hp;
int fd;
int len;
int buflen;
char buf[1024];
int ret;
if (argc != 2){
printf("Usage: iclient SERVER_NAME\n");
exit(1);
}
/*
* ソケットを作る。このソケットはUNIXドメインで、DGRAM型ソケット。
*/
if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror("socket");
exit(1);
}
/*
* addrの中身を0にしておかないと、bind()でエラーが起こることがある
*/
bzero((char *)&saddr, sizeof(saddr));
/*
* ソケットに名前を入れておく
*/
if ((hp = gethostbyname(argv[1])) == NULL) {
perror("No such host");
exit(1);
}
bcopy(hp->h_addr, &saddr.sin_addr, hp->h_length);
saddr.sin_family = AF_INET;
saddr.sin_port = htons(PORT);
/*
* STREAM型のときは、ここでconnect()を呼んでいた。
*/
/*
* 入力されたデータをソケットに書き込んでサーバーに送り、
* サーバーが変換して送ってきたデータを読み込む。
*/
while (fgets(buf, 1024, stdin)) {
buflen = strlen(buf);
/* 送信は、sendto()で行う */
if (sendto(fd, buf, buflen, 0, (struct sockaddr *)&saddr, sizeof(saddr)) != buflen){
perror("sendto");
exit(1);
}
/* 受信はrecvfrom()で行う */
if ((ret = recvfrom(fd, buf, 1024, 0, NULL, &len)) < 0) {
perror("recvfrom");
exit(1);
}
buf[ret] = '\0';
printf("%s",buf);
}
close(fd);
exit(0);
}