gpt4 book ai didi

c - 使用 newSocket.sin_port = htons(portNumber) 将端口号分配给套接字时出错;

转载 作者:太空宇宙 更新时间:2023-11-04 08:55:52 24 4
gpt4 key购买 nike

我正在尝试分配函数传递给它的端口号。收到的端口号在收到时正确显示,但是当我尝试将该端口号分配给新的套接字时,该端口号未分配,并且每次都分配了其他一些号码 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 个字符(包括终止符)。

因此您可能会遇到缓冲区溢出,从而导致未定义的行为。

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

关于c - 使用 newSocket.sin_port = htons(portNumber) 将端口号分配给套接字时出错;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17062687/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com