server.c

来自「unix高级编程开发环境」· C语言 代码 · 共 86 行

C
86
字号
/* server.c */
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdlib.h>
#define MYPORT 1234 #define BACKLOG 10
#define DEFAULT_IP "127.0.0.1"
int main(){	int sockzw,sockbd,newzw,sin_size;	struct sockaddr_in my_addr;	struct sockaddr_in cl_addr;		sockzw = socket(AF_INET, SOCK_STREAM, 0); 	my_addr.sin_family = AF_INET; /* host byte order */ 	my_addr.sin_port = htons(MYPORT); /* short, network byte order */ 	my_addr.sin_addr.s_addr = inet_addr(DEFAULT_IP); 	bzero(&(my_addr.sin_zero),8); /* zero the rest of the struct */	printf("the IPADDR is:%d\n",sockzw); 		/* don't forget your error checking for bind(): */ 	sockbd = bind(sockzw,(struct sockaddr*)&my_addr,sizeof(struct sockaddr));	printf("the sockbd is :%d\n",sockbd);	if (sockbd==-1)	{		perror("bind failure!\n");	}	else	{			printf("bind success!\n"); 	}	if (listen(sockzw, BACKLOG) == -1)	{		perror("listen.....");		exit(1);	}	else	{		printf("listen success!\n");	}	while(1)	{		printf("Waiting for client!\n");		sin_size = sizeof(struct sockaddr_in);		if ((newzw = accept(sockzw,(struct sockaddr*)&cl_addr,&sin_size)) == -1)		{			perror("accept....");			continue;  		}		else		{			printf("accept success!\n");		}		if (!fork())		{			if (send(newzw,"hello,world!\n",14,0)==-1)			{				perror("send.....");				close(newzw);				exit(0);			}			printf("send success!\n");			close(newzw);		}		waitpid(-1,NULL,WNOHANG)>0;	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?