I am trying to assign port number passed to it by a function. The port number received is displayed correctly when received but when I try to assign that port number to a new Socket, that port number is not assigned and some other number 52428 is assigned everytime. I tried my best to figure out the error myself but I failed :( Please help me. Below is my code:
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*/
}
The string buffer ipNumber
is too small. It's only 12 characters, but a full IP might be "255.255.255.255"
which is 16 characters (including the terminator).
So you might have a buffer overrun, leading to undefined behavior.
You should use a debugger to look in the various fields of the structs, to see that all is well.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.