[[Net003]]

* 単純な server program [#e4a92e2a]

 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <sys/types.h>
 #include <sys/socket.h>
 #include <netdb.h>
 #include <unistd.h>
 #include <errno.h>
 extern int errno;
 
 int main(int argc, char* argv[])
 {
 	struct sockaddr_in saddr;
 	struct sockaddr_in caddr;
 	socklen_t calen;
 
 	int sd;
 	int cd;
 	int port;
 
 	/* Check the command-line arguments */
 	if(argc != 2)
 	{
 		fprintf(stderr, "Usage: %s port\n", argv[0]);
 		return (-1);
 	}
 	
 	port = atoi(argv[1]);
 	if(port <= 0)
 	{
 		fprintf(stderr, "Illegal port number (%d)\n", port);
 		return (-1);
 	}
 
 	/* Set the server address */
 	memset(&saddr, 0, sizeof(saddr));
 	memset(&caddr, 0, sizeof(caddr));
 
 	saddr.sin_family = AF_INET;
 	saddr.sin_port = htons((u_short)port);
 	saddr.sin_addr.s_addr = INADDR_ANY;
 
 	/* Create socket for listen port and bind the server address */
 	if((sd = socket( PF_INET, SOCK_STREAM, 0)) == -1)
 		return errno;
 	if(bind(sd, (const struct sockaddr*)&saddr, sizeof(saddr)) == -1)
 	{
 		close(sd);
 		return errno;
 	}
 
 	/* Listen the service port */
 	if(listen(sd, 5) == -1)
 	{
 		close(sd);
 		return errno;
 	}
 
 	while(1)
 	{
 		/* Clear the address for accept */
 		memset(&caddr, 0, sizeof(caddr));
 		calen = sizeof(caddr);
 		/* Dequeue the connection requested in the listen socket */
 		/* Dequeue the requested connection in the listen socket */
 		if((cd = accept(sd,(struct sockaddr*)&caddr, &calen)) == -1)
 		{
 			close(sd);
 			return errno;
 		}
 		send(cd, "Hello\r\n", 7, 0);
 		close(cd);
 	}
 
 	/* Server done. (Never come) */
 	close(sd);
 	return 0;
 }

トップ   編集 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS