none
tcp中关于sprintf的用法问题。应如何解决?? RRS feed

  • 问题

  • 一个tcp程序,调试后失败,输出显示:error C4996: 'sprintf': This function or variable may be unsafe. Consider using sprintf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.     c:\program files\microsoft visual studio 11.0\vc\include\stdio.h(357) : 参见“sprintf”的声明 。 全代码如下
    void main()
    {
    	WORD wVersionRequested;
    	WSADATA wsaData;
    	int err;
    
    	wVersionRequested = MAKEWORD(1,1);
    	
    	err = WSAStartup (wVersionRequested , &wsaData);
    	if ( err != 0) {
    		return;
    	}
    
    	if (LOBYTE (wsaData.wVersion) != 1  ||  HIBYTE(wsaData.wVersion) != 1)
    	{
    		WSACleanup ();
    		return;
    	}
    
    	SOCKET socksrv=socket(AF_INET,SOCK_STREAM,0);
    
    	SOCKADDR_IN addrsrv;
    	addrsrv.sin_addr .S_un.S_addr=htonl(INADDR_ANY);
    	addrsrv.sin_family=AF_INET;
    	addrsrv.sin_port=htons(6000);
    
    	bind(socksrv,(SOCKADDR*)&addrsrv,sizeof(SOCKADDR));
    
    	listen(socksrv,5);
    
    	SOCKADDR_IN addrclient;
    	int len = sizeof (SOCKADDR);
    
    	while(1)
    	{
    		SOCKET sockconn= accept (socksrv,(SOCKADDR*)&addrclient,&len);
    		char sendBuf[100];
    		sprintf(sendBuf,"Welcome %s home",
    			inet_ntoa(addrclient.sin_addr));
            send(sockconn,sendBuf ,strlen(sendBuf)+1,0);
    		char recvbuf[100];recv(sockconn,recvbuf,100,0);
    		printf("%s\n",recvbuf);
    		closesocket(sockconn);
    	}
    }

    2014年5月25日 7:43

答案

  • 这个应该是警告,而不是个错误吧。您可以使用sprintf_s来替换sprintf。

    Visual C++ enthusiast, like network programming and driver development. At present is being engaged in the WinCE/Windows Mobile platform embedded development.

    2014年5月25日 11:58
    版主