在何时安全释放传递给 bind 的 sockaddr?

huangapple go评论62阅读模式
英文:

When is it safe to free sockaddr passed to bind?

问题

Bind 函数期望接收一个指向 struct sockaddr 的指针 (https://man7.org/linux/man-pages/man2/bind.2.html)。在调用 bind 后立即释放这个结构体是安全的吗,还是只有在套接字关闭时才安全释放它?

如果在调用 bind 后立即释放这个结构体是安全的,那么内核是否会保留地址的副本?

英文:

Bind expects a pointer to struct sockaddr (https://man7.org/linux/man-pages/man2/bind.2.html). Is it safe to free this structure immediately after the call to bind or is it safe to free this only when the socket is closed?

If it is safe to free the structure immediately after the call to bind, does the kernel keep a copy of the address?

答案1

得分: 2

你可以在调用后立即释放它。

通常,sockaddrsockaddr_in 在堆栈上声明。但是,如果你通过指针传递地址,你可以在bind返回后立即释放它。对于其他套接字函数,比如connectsendto,情况也是一样的。

英文:

You can free it immediately after the call.

Usually the sockaddr or sockaddr_in is declared on the stack. But if you're passing addresses around by pointer, you're ok free it immediately after bind returns. Same holds true for other socket functions like connect and sendto.

答案2

得分: 2

这是安全的释放。如您可以在Linux源代码中的注释中看到的那样,该结构由内核复制。

我们在调用协议层之前将套接字地址移动到内核空间(还检查地址是否正常)。

英文:

It is safe to free. As you can see in the comments to the Linux source for the syscall, the structure is copied by the kernel.

> * We move the socket address to kernel space before we call * the
> protocol layer (having also checked the address is ok).

huangapple
  • 本文由 发表于 2023年2月27日 13:47:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75577109.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定