为什么我们在调用bind()时将sockaddr_in转换为sockaddr?

时间:2022-09-11 19:08:43

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:

bind()函数接受一个指向sockaddr的指针,但是在我看过的所有例子中,都使用了sockaddr_in结构,并将其强制转换为sockaddr:

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

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

我无法理解为什么使用sockaddr_in结构。为什么不准备并通过一个sockaddr?

Is it just convention?

这只是惯例吗?

2 个解决方案

#1


43  

No, it's not just convention.

不,这不仅仅是惯例。

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是任何类型的套接字操作的通用描述符,而sockaddr_in是特定于基于IP的通信的结构(IIRC,“in”代表“InterNet”)。据我所知,这是一种“多态”:bind()函数假装采用struct sockaddr *,但事实上,它会假设传入适当类型的结构;一世。即一个与你给它作为第一个参数的套接字类型相对应的一个。

#2


4  

This is because bind can bind other types of sockets than IP sockets, for instance Unix domain sockets, which have sockaddr_un as their type. The address for an AF_INET socket has the host and port as their address, whereas an AF_UNIX socket has a filesystem path.

这是因为bind可以绑定除IP套接字之外的其他类型的套接字,例如Unix域套接字,它们的类型为sockaddr_un。 AF_INET套接字的地址将主机和端口作为其地址,而AF_UNIX套接字具有文件系统路径。

#1


43  

No, it's not just convention.

不,这不仅仅是惯例。

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是任何类型的套接字操作的通用描述符,而sockaddr_in是特定于基于IP的通信的结构(IIRC,“in”代表“InterNet”)。据我所知,这是一种“多态”:bind()函数假装采用struct sockaddr *,但事实上,它会假设传入适当类型的结构;一世。即一个与你给它作为第一个参数的套接字类型相对应的一个。

#2


4  

This is because bind can bind other types of sockets than IP sockets, for instance Unix domain sockets, which have sockaddr_un as their type. The address for an AF_INET socket has the host and port as their address, whereas an AF_UNIX socket has a filesystem path.

这是因为bind可以绑定除IP套接字之外的其他类型的套接字,例如Unix域套接字,它们的类型为sockaddr_un。 AF_INET套接字的地址将主机和端口作为其地址,而AF_UNIX套接字具有文件系统路径。