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

查看:202
本文介绍了为什么我们投有sockaddr_in调用bind时转换为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 结构用我不能换我周围的头。为什么不干脆prepare和传递的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,)的通信。据我所知,这是一种多态:在绑定()函数pretends采取结构sockaddr * ,但实际上,它会假设结构的相应类型的传递;一世。即对应于插座的类型有一个你给它的第一个参数。

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.

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

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