C++ socket网络编程笔记(服务端3) 完整代码

上篇:

https://blog.csdn.net/m0_46480482/article/details/122995226

完整代码:

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


#define SERVER_PORT 666

int main(void)
{
	int sock;// represent mailbox
	struct sockaddr_in server_addr;// tag

	//create mailbox
	sock = socket(AF_INET,SOCK_STREAM,0);
	
	//1 clear tag first 
	bzero(&server_addr,sizeof(server_addr));
	//2 set intnet protocol = IPV4
	server_addr.sin_family = AF_INET;
	//3 bind ip addr (all local addr)
	server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	//4 set port num
	server_addr.sin_port =  htons(SERVER_PORT);


	// bind tag to mailbox
	bind(sock,(struct sockaddr *)&server_addr,sizeof(server_addr));

	// listening max 128 message at the same time 
	listen(sock,128);
	
	printf("waiting for client link\n");


	int done=1;
	
	while(done)
	{
		struct sockaddr_in client;
		int client_sock,len;
		char client_ip[64];
		char buf[256];

		socklen_t client_addr_len;
		client_addr_len = sizeof(client);
		client_sock = accept(sock,(struct sockaddr *)&client , &client_addr_len);
		
		printf("client ip:%s\t port: %d\n",
			inet_ntop(AF_INET,&client.sin_addr.s_addr,client_ip,sizeof(client_ip)),
				ntohs(client.sin_port));


		//read client server's data
		len = read(client_sock,buf,sizeof(buf)-1);
		buf[len]='\0';
		printf("recive[%d]: %s\n",len,buf);

		// process message
		for(int i=0;i='a'&& buf[i]<='z')
				buf[i]-=32;
		}
		len = write(client_sock,buf,len);

		printf("len:%d\nsend_message:%s\nFinished.",len,buf);
		close(client_sock);
		done = 0 ;
	}
	close(sock);
	return 0;
}

你可能感兴趣的:(网络,c++,linux,ubuntu,socket)