c - 为什么从 sockaddr_in 到 sockaddr 的转换有效

标签 c linux sockets bind

在 C 语言中,绑定(bind) Socket 的典型方式如下:

int server_socket_fd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in addr;
int port_number = 55555;

addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(port_number);

int result = bind(server_socket_fd,(struct sockaddr *)&addr , sizeof(addr));
if(bind_result > 0)
{
    // Stuff
}

我想知道为什么从 sockaddr_insockaddr 的转换有效,因为我找不到任何说明它有效的文档。 似乎每个人都这样做。

为什么类型转换在这里起作用?

我不是在问我们为什么投它,这已经被回答了here .我在问为什么它有效。

最佳答案

允许将结构指针转换为不同的结构指针并返回。这在 C standard 的第 6.3.2.3p7 节中有详细说明。 :

A pointer to an object type may be converted to a pointer to a different object type. If the resulting pointer is not correctly aligned for the referenced type, the behavior is undefined. Otherwise, when converted back again, the result shall compare equal to the original pointer. When a pointer to an object is converted to a pointer to a character type, the result points to the lowest addressed byte of the object. Successive increments of the result, up to the size of the object, yield pointers to the remaining bytes of the object.

上述段落中关于对齐的限制在 6.2.5p28 节中有进一步详细说明:

A pointer to void shall have the same representation and alignment requirements as a pointer to a character type.48) Similarly, pointers to qualified or unqualified versions of compatible types shall have the same representation and alignment requirements. All pointers to structure types shall have the same representation and alignment requirements as each other. All pointers to union types shall have the same representation and alignment requirements as each other. Pointers to other types need not have the same representation or alignment requirements.

据推测,bind 函数知道它拥有哪种套接字描述符并将 struct sockaddr * 转换回 struct sockaddr_in *

关于c - 为什么从 sockaddr_in 到 sockaddr 的转换有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51287930/

相关文章:

c - OpenCV 获取/设置 IplImage RGB 值

我们可以使用之前释放的指针吗?

linux - 一个线程获取信号量而另一个线程释放信号量的有效用例是什么?

linux - 在具有多个 Controller 的服务器中分配内存时,操作系统是否会选择内存 Controller ?如何?

c - 如何检查 C 中的特定端口是否可以访问远程主机?

c++ - MPI_Send 错误

c - 为什么一段代码在迭代一定次数后会一直不停地运行?

c - 程序在 setuid 和 setgid 之后仍然能够打开 root only 文件

java - 如何使用带有证书的 Apache Commons SSLServer/SSLClient

python - 在运行的进程中刷新paramiko中的stdout