tcpserver.c

/*
vim tcpserver.c
gcc -o tcpserver tcpserver.c
./tcpserver
netstat -ap|grep tcpserver
*/
#include    
#include 
#include 
#include 
#include 
#include 
int mian()
{
     
	int skfd;//socket文件描述符 socket file description 
	socklen_t addrlen;
	int ret;
	char buff[20];
	
	struct sockaddr_in serveraddr,clientaddr;
	skfd = socket(AF_INEF,SOCK_STREAM,0);
	if(skfd<0)
	{
     
	  perror("socket");
	  return -1;	
	}
	//填充网络类型,端口号,ip地址
	serveraddr.sin_family = AF_INEF;//填充网络地址类型 IPv4
	serveraddr.sin_port = htons(55555);//注意 端口号是short htons是字节序转换
	serveraddr.sin_addr.s_addr = 0;//inet_addr(""0,0,0,0);写0表示绑定任意地址
	addrlen = sizeof(serveraddr);
	ret = bind(skfd,(struct sockaddr *)&serveraddr,addrlen);
	if(ret<0)
	{
     
	  perror("bind");
	  return -1;	
	}	
	ret = listen(skfd,5);//5表示可以同时连接客户端的数量
	if(ret<0)
	{
     
	  perror("listen");
	  return -1;	
	}
	while(1)
	{
     
		int clientfd;//client文件描述符 client file description 
		clientfd = accept(skfd,(struct sockaddr *)&clientaddr,&addrlen);
		
		if(clientfd<0)
		{
     
		  perror("accept");
		  return -1;	
		}
		printf("ret=%d,ip:%s,port:%d\n",clientfd,inet_ntao(clientaddr.sin_addr,ntohs(clientaddr.sin_port)));
		int recvlen=0;		
		if(clientfd>0)
		{
     
			while(1)
			{
     
				memset(buff,0,MSGLEN);
				recvlen = recv(clientfd,buff,10,0);
				if(recvlen==0)
				{
     
					printf("connect:%d closeed\n",clientfd);
					close(clientfd);
					break;		
				}
				printf("recvlen:%d,%s\n",recvlen,buff);
			}
		}
		close(skfd);
	}
}

你可能感兴趣的:(STM32)