TCP服务端

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

typedef struct sockaddr* SP;


void server(int cli_fd)
{
	char buf[4096] ={};
	size_t buf_size = sizeof(buf);

	for(;;)
	{
		//接收请求
		int ret = read(cli_fd,buf,buf_size);
		if(0 >= ret || 0 == strcmp(buf,"quit"))
		{
			printf("客户端%d 退出\n",cli_fd);
			break;
		}
		printf("from %d recv: %s bits:%d\n",cli_fd,buf,ret);

		//响应请求
		strcat(buf,":return");
		ret = write(cli_fd,buf,strlen(buf)+1);
		if(0 >= ret)
		{
			printf("客户端%d 退出\n",cli_fd);
			break;
		}
	}
	//关闭cli_socket
	close(cli_fd);
}

int main()
{
	//创建socket
	int sockfd = socket(AF_INET,SOCK_STREAM,0);
	if(0 > sockfd)
	{
		perror("socket");
		return EXIT_FAILURE;
	}

	//准备通信地址
	struct sockaddr_in addr = {};
	addr.sin_family = AF_INET;
	addr.sin_port = htons(6666);
	addr.sin_addr.s_addr = inet_addr("172.16.3.102");//服务端绑定本机ip
	socklen_t addrlen = sizeof(addr);

	//绑定
	if(bind(sockfd,(SP)&addr,addrlen))
	{
		perror("bind");
		return EXIT_FAILURE;
	}

	//监听
	if(listen(sockfd,5))
	{
		perror("listen");
		return EXIT_FAILURE;
	}

	for(;;)
	{
		struct sockaddr_in cli_addr = {};

		//等待连接
		int cli_fd = accept(sockfd,(SP)&cli_addr,&addrlen);
		if(0 > cli_fd)
		{
			perror("accept");
			continue;
		}
		
		//创建进程服务
		if(0 == fork())
		{
			server(cli_fd);
		}
	}
}

你可能感兴趣的:(面试知识点,tcp/ip,网络,网络协议)