`
bollaxu
  • 浏览: 220779 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

accept的Invalid Argument错误

 
阅读更多

在编写socket程序的时候,遇到一个奇怪的问题,服务端用accept接收请求,客户端通过telnet连接上去。结果每次连上去以后连接又立即断开了,而server端accept以后并没有close连接。

 

代码如下:

/*server*/
int main()
{
	//...
	socklen_t cli_len;
	struct sockaddr_in clientaddr;
	
	while(1)
	{
		int connfd = accept(listenfd, (struct sockaddr *)&clientaddr, &cli_len);
		if(connfd < 0)
		{
			perror("accept");
		}
		
		//...
	}
	
	return 0;
}

 最后发现是初始化的问题,cli_len和clientaddr不能为负值,因为上面没有初始化,所以在accept的时候会出问题。最后加上初始化的代码,问题就解决了。

/*server*/
int main()
{
	//...
	socklen_t cli_len;
	struct sockaddr_in clientaddr;
	
	while(1)
	{
		memset(&clientaddr, 0, sizeof(struct sockaddr_in));
		cli_len = 1;
		int connfd = accept(listenfd, (struct sockaddr *)&clientaddr, &cli_len);
		if(connfd < 0)
		{
			perror("accept");
		}
		
		//...
	}
	
	return 0;
}
 
分享到:
评论

相关推荐

    2009 达内Unix学习笔记

    集合了 所有的 Unix命令大全 ...telnet 192.168.0.23 自己帐号 sd08077-you0 ftp工具 192.168.0.202 tools-toolss ... 各个 shell 可互相切换 ksh:$ sh:$ csh:guangzhou% bash:bash-3.00$ ... 命令和参数之间必需用空格隔...

    springframework.5.0.12.RELEASE

    MockMvcResultMatchers.forwardedUrl argument is not declared as nullable [SPR-17623] #22155 Cannot convert from Collection to RegularEnumSet [SPR-17619] #22151 TomcatHttpHandlerAdapter is not aware of ...

    python3.6.5参考手册 chm

    PEP 468: Preserving Keyword Argument Order New dict implementation PEP 523: Adding a frame evaluation API to CPython PYTHONMALLOC environment variable DTrace and SystemTap probing support Other ...

    Universal-USB-Installer

    安装linux工具源码 (UUI) Universal USB Installer ?...This Open Source tool falls under the GNU General Public License Version 2 Source Code is made available at time of download, from the official UUI ...

    EurekaLog_7.5.0.0_Enterprise

    8)....Fixed: Silently ignore and fix invalid values in project options EurekaLog 7.2 Hotfix 2 (7.2.2.0), 30-April-2015 1)....Fixed: Confusing message in Manage tool when using with Trial/Pro 2).......

    WizFlow网页编辑

    the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or ...

    hibernate-shards.jar

    the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or ...

    servlet2.4doc

    Overview Package Class Tree Deprecated Index Help PREV NEXT FRAMES NO FRAMES A B C D E F G H I J L P R S U V -------------------------------------------------------------------------------- ...

Global site tag (gtag.js) - Google Analytics