Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用newSocket.sin_port=htons(端口号)为套接字分配端口号时出错;_C_Windows_Sockets_Visual Studio 2008_Network Programming - Fatal编程技术网

使用newSocket.sin_port=htons(端口号)为套接字分配端口号时出错;

使用newSocket.sin_port=htons(端口号)为套接字分配端口号时出错;,c,windows,sockets,visual-studio-2008,network-programming,C,Windows,Sockets,Visual Studio 2008,Network Programming,我试图分配一个函数传递给它的端口号。接收到的端口号在接收时正确显示,但当我尝试将该端口号分配给新插槽时,该端口号未分配,并且每次都分配其他一些52428号。我自己尽了最大努力想找出错误,但失败了:(请帮助我。下面是我的代码: DWORD WINAPI newrecvThreadProcedure(LPVOID param) { newRecvThreadDetailStruct* myDetailStruct = (newRecvThreadDetailStruct*) (

我试图分配一个函数传递给它的端口号。接收到的端口号在接收时正确显示,但当我尝试将该端口号分配给新插槽时,该端口号未分配,并且每次都分配其他一些52428号。我自己尽了最大努力想找出错误,但失败了:(请帮助我。下面是我的代码:

DWORD WINAPI newrecvThreadProcedure(LPVOID param)
{       
   newRecvThreadDetailStruct* myDetailStruct =  (newRecvThreadDetailStruct*) (param);
   char ipNumber[12], newDetail[256], threadNumber_char[12], 
        *detail =    myDetailStruct>newsocketDetail;
   int portNumber, threadNumber_int = myDetailStruct->threadNum; 
   sscanf(detail,"%s %d",ipNumber,&portNumber);
   char displayPortNum[12];
   itoa(portNumber,displayPortNum,10);
   MessageBox( NULL, displayPortNum,"portnumber", MB_ICONINFORMATION); //Port Number displayed here is the value that I want i.e. 8880 
// =======================================================================================
// Creating New Socket Now
   WSADATA wsa; 

   //Initialise winsock
   if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
      {
    //"WinSock Initialization FAILED"
        return 0;
      }

   //Create a socket
   SOCKET newSocketIdentifier;
   SOCKADDR_IN newSocket;
   if((newSocketIdentifier = socket(AF_INET , SOCK_DGRAM , 0 )) == INVALID_SOCKET)
      {
        //"Socket Creation Failed",
         exit(EXIT_FAILURE);
      }
   //Socket Created

   //Prepare the sockaddr_in structure
   newSocket.sin_family = AF_INET;
   newSocket.sin_addr.s_addr = INADDR_ANY;
   newSocket.sin_port = htons(portNumber);
   char char_port[12],*client_ip = inet_ntoa(newSocket.sin_addr); 
   int int_port = ntohs(newSocket.sin_port);
   itoa(int_port,char_port,10);
   MessageBox( NULL,char_port,client_ip,MB_ICONEXCLAMATION | MB_OK);  /* Port number 
displayed here is 52428 and IP Address is 0.0.0.0*/
}

字符串缓冲区
ipNumber
太小。它只有12个字符,但完整IP可能是
“255.255.255.255”
,即16个字符(包括终止符)

因此,可能会出现缓冲区溢出,导致未定义的行为

您应该使用调试器查看结构的各个字段,以确保一切正常