[英]addrinfo struct not retaining values after function call
I have a static addrinfo struct being used to save the results of my call to getaddressinfo() within the static function init_socket().我有一个 static addrinfo 结构用于保存我在 static function init_socket() 中调用 getaddressinfo() 的结果Inside the init_socket() the addrinfo struct has the correct values, but on return it gets zeroed.
在 init_socket() 内部,addrinfo 结构具有正确的值,但在返回时它被归零。
Code below of what I am trying to accomplish.下面是我想要完成的代码。
static struct addrinfo rxRes;
static int init_socket(struct addrinfo *resInfo, char *host, char *port) {
struct addrinfo hints;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_DGRAM;
if (!host) { // automatically assign ip to result ip of current machine
hints.ai_flags = AI_PASSIVE;
}
int res = getaddrinfo(host, port, &hints, &resInfo);
if (res != 0 || !resInfo) {
PRINT_NET_ERR(res);
exit(EXIT_FAILURE);
}
printf("init addrlen: %d\n", resInfo->ai_addrlen); // correct output
return socket(resInfo->ai_family, resInfo->ai_socktype, resInfo->ai_protocol);
}
int main(int argc, char *argv[])
{
/* initialize socket connections */
int rxsFD = init_socket(&rxRes, TEST_HOST, TEST_PORT);
printf("main addrlen: %d\n, rxRes.ai_addrlen) // outputs 0
...
}
resInfo
is a local variable in the function so any changes to it will not be reflected in the caller. resInfo
是 function 中的局部变量,因此对它的任何更改都不会反映在调用者中。 The caller needs to pass in a pointer to a pointer and not just a pointer.调用者需要传入一个指向指针的指针,而不仅仅是一个指针。 The
getaddinfo
will allocate dynamic memory. getaddinfo
将分配动态 memory。 Yes, it is a little confusing so please see the following corrected code which hopefully makes it clearer.是的,这有点令人困惑,所以请查看以下更正的代码,希望它更清晰。
static int init_socket(struct addrinfo **resInfo, char *host, char *port) {
..
int res = getaddrinfo(host, port, &hints, resInfo);
..
}
int main(int argc, char *argv[])
{
struct addrinfo *rxRes;
/* initialize socket connections */
int rxsFD = init_socket(&rxRes, TEST_HOST, TEST_PORT);
printf("main addrlen: %d\n, rxRes->ai_addrlen);
/* free the result when no longer needed */
freeaddrinfo(rxRes);
...
}
Complementing the answer:补充答案:
I think you will need to use another pointer to access the addrinfo struct
inside the function init_socket()
for the purpose of the return
using the socket()
function.我认为您需要使用另一个指针来访问 function
init_socket()
中的addrinfo struct
,以便使用socket()
function return
。
So you can do it:所以你可以这样做:
struct addrinfo *addrRet = *resInfo;
printf("initsocket: %d\n", addrRet->ai_addrlen);
return socket(addrRet->ai_family, addrRet->ai_socktype, addrRet->ai_protocol);
Sorry by the answer.对不起,答案。 I can't write a comment (no reputation).
我不能写评论(没有声誉)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.