本文介绍了Listen()和accept()系统调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经了解了listen调用的工作原理以及对其中使用的backlog参数的用法。但是我想看看这个(积压数量的队列)是如何在核心水平上运作的。



我尝试了什么:



I have read about how listen call works and what is use of backlog argument given into it. But I want to see how this (queue of number of backlog ) works at kernal level.

What I have tried:

/*
Exicute : 	gcc -o server inet4_server.c
			./server <portid> <networkid>
*/
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#define BUF_SIZE 1024
int main(int argc,char *argv[])
{
	int sfd,newsockfd,cli_len=0,ret,data_len;
	struct sockaddr_in seraddr,cliaddr;
	char buffer[BUF_SIZE];
	char c_addr[256];
	if(argc < 3)
	{
		printf("Execute it with command line arguments like:\n ./socket portid(i.e.9055) networkip(10.102.1.181)\n");
		printf("Or for loop back ./socket portid(i.e.9055) networkip(0.0.0.0)\n");
		return 1;
	}
	sfd=socket(AF_INET,SOCK_STREAM,0);
	if(sfd<0)
	{
		perror("Error in socket\n");
		close(sfd);
		return;
	}
	printf("Socket Is Created\n");
	seraddr.sin_family=AF_INET;
	seraddr.sin_addr.s_addr=inet_addr(argv[2]);
	seraddr.sin_port=htons(atoi(argv[1]));
	memset(seraddr.sin_zero,'\0',sizeof(seraddr.sin_zero));
	
	if(bind(sfd,(struct sockaddr *)&seraddr,sizeof(seraddr))<0)
	{
		perror("Error in bind");
		close(sfd);
		return;
	}
	printf("Bind Is Done\n");
	listen(sfd,3);
	printf("Listening..........\n");
	
	while(1)
	{
		struct sockaddr_in cliaddr;
		cli_len=sizeof (cliaddr);
		newsockfd=accept(sfd,(struct sockaddr *)&cliaddr,&cli_len);
		if(newsockfd<0)
	    {
	    	perror("Error in accept\n");
			exit(1);
		}
		inet_ntop(AF_INET, &(cliaddr.sin_addr), c_addr, sizeof(c_addr));
		printf("COnnection from Port : %d and IP : %s\n",(int)(htons(cliaddr.sin_port)), c_addr);

	    while(1)
	    {
	    	memset(buffer,0,BUF_SIZE);
	    	data_len = recv(newsockfd,buffer,BUF_SIZE,0);
	    	if(data_len < 0)
	    	{
	    		perror("Error in recv()\n");
	    	}
	    	printf("Received : %s\n",buffer);
	    	printf("Reply to client : ");
	    	fgets(buffer, BUF_SIZE, stdin);
	    	send(newsockfd,buffer,BUF_SIZE,0);
	    }
	    printf("Client Is Closed\n"); 
	    close(newsockfd);
	}
	close(sfd);   
}

推荐答案


这篇关于Listen()和accept()系统调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 22:34