为什么我们在调用 bind() 时将 sockaddr_in 转换为 sockaddr? [英] Why do we cast sockaddr_in to sockaddr when calling bind()?

查看:40
本文介绍了为什么我们在调用 bind() 时将 sockaddr_in 转换为 sockaddr?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

bind() 函数接受一个指向 sockaddr 的指针,但在我见过的所有示例都使用了 sockaddr_in 结构,并转换为 sockaddr:

The bind() function accepts a pointer to a sockaddr, but in all examples I've seen, a sockaddr_in structure is used instead, and is cast to sockaddr:

struct sockaddr_in name;
...
if (bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0)
...

我无法理解为什么使用了 sockaddr_in 结构.为什么不直接准备并传递一个 sockaddr?

I can't wrap my head around why is a sockaddr_in struct used. Why not just prepare and pass a sockaddr?

这只是惯例吗?

推荐答案

不,这不仅仅是惯例.

sockaddr 是任何类型的套接字操作的通用描述符,而 sockaddr_in 是特定于基于 IP 的通信的结构(IIRC,in"代表Internet").据我所知,这是一种多态":bind() 函数假装采用一个 struct sockaddr *,但实际上,它会假设传入合适的结构类型;一世.e.一个对应于你给它作为第一个参数的套接字类型.

sockaddr is a generic descriptor for any kind of socket operation, whereas sockaddr_in is a struct specific to IP-based communication (IIRC, "in" stands for "InterNet"). As far as I know, this is a kind of "polymorphism" : the bind() function pretends to take a struct sockaddr *, but in fact, it will assume that the appropriate type of structure is passed in; i. e. one that corresponds to the type of socket you give it as the first argument.

这篇关于为什么我们在调用 bind() 时将 sockaddr_in 转换为 sockaddr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆