/***********************************************************************
server.c : simple internet socket server program
Jan 8,2001 copyright Takeshi FUJIKI (fujiki@fc-lab.com)
入力された数値を加算して結果を返すサーバ
***********************************************************************/
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#define BUFLEN 4096
#define LISTEN_PORT 7000
main(int argc, char *argv[]) {
struct hostent *thishost;
struct sockaddr_in me;
char hostname[80],buf[BUFLEN],*message;
int connected_socket, listen_socket, option;
int n, sum;
gethostname(hostname,80);
thishost = gethostbyname(hostname);
bzero((char *)&me,sizeof(me));
me.sin_family=AF_INET;
me.sin_port = htons(LISTEN_PORT);
bcopy(thishost->h_addr,(char *)&me.sin_addr,thishost->h_length);
listen_socket = socket(AF_INET,SOCK_STREAM,0);
option = 1;
setsockopt(listen_socket,SOL_SOCKET,SO_REUSEADDR,&option,sizeof(option));
bind(listen_socket, &me,sizeof(me));
listen(listen_socket,1);
connected_socket = accept(listen_socket,NULL,NULL);
close(listen_socket);
message = "Please input numbers!\n";
write(connected_socket,message,strlen(message));
sum = 0;
do {
n = read(connected_socket,buf,BUFLEN);
buf[n]='\0';
sum += atoi(buf);
} while(n > 2);
sprintf(buf,"sum : %d\n",sum);
write(connected_socket,buf,strlen(buf));
close(connected_socket);
}
|