システムプログラム02-ver01_client

/* pp.215-217 */
/* connects to the local host at port 1234 */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#define NSTRS 3 /* 文字列の個数 */
#define STRMAX 10

/*
* サーバに送る文字列を作成する
*/

char *strs[NSTRS];

extern int errono;

void input_strs(){
int i;
char e[]="\n";
for(i=0;i<NSTRS;i++){
printf("str[%d]:",i);
strs[i]=malloc(STRMAX);
gets(strs[i]);
strcat(strs[i],e);
}
}

int main(int ac, char *av[]){
char c;
FILE *fp;
char hostname[64];
register int i,s;
struct hostent *hp;
struct sockaddr_in sin;


printf(">> client run\n");

/*
* まずホストネームを取得
*/
printf("__connect server name ? :");
gets(hostname);
input_strs();

/* gethostname(hostname,sizeof(hostname));
*/

/*
* つぎに、ホストのネットワークアドレスを取得
*/
if((hp=gethostbyname(hostname))==NULL){
fprintf(stderr,"%s: unknown host.\n", hostname);
exit(1);
}

/*
* 通信用ソケットを取得、このソケットはインターネット
* ドメインで、ストリーム型(接続型)である
*/
if((s=socket(AF_INET,SOCK_STREAM,0))<0){
perror("clisent: socket");
exit(1);
}

/*
* 接続先のネットワークアドレス情報を作成する
* ここではポート番号として、9000を使用する
* 整数値はネットワークバイトオーダーに直すことに注意
* データはbcopyを用いて、構造体に格納する
*/
sin.sin_family=AF_INET;
sin.sin_port=htons(9000);
bcopy(hp->h_addr,&sin.sin_addr,hp->h_length);

/*
* 上記アドレスに接続を試みる。この接続が成功するためには
* それまでにサーバー側で上記アドレスを取得し、listen()
* システムコールを呼び出していなければならない
*/
if(connect(s, (struct sockaddr*)&sin, sizeof(sin))<0){
perror("client: connect");
exit(1);
}


/*
* こちらから文字列をサーバーに送る
*/
for(i=0;i<NSTRS;i++)
send(s,strs[i],strlen(strs[i]),0);
/*
* ソケットからデータを読み出すためのファイルポインタ
*/
fp=fdopen(s,"r");

/*
*サーバーから文字列を読み取り、それをプリントする。
*/
printf(">> text from server\n");
for(i=0;i<NSTRS;i++){
strs[i]=malloc(STRMAX);
fgets(strs[i],STRMAX,fp);
printf("%s",strs[i]);
}

/*
*ここで、通信を切断するために、close()を用いる
*/
close(s);

exit(0);
}

タグ:

+ タグ編集
  • タグ:

このサイトはreCAPTCHAによって保護されており、Googleの プライバシーポリシー利用規約 が適用されます。

最終更新:2010年07月13日 20:59