Why do we cast sockaddr_in to sockaddr when callin

2019-01-10 08:18发布

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)
...

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

Is it just convention?

标签: c linux sockets
2条回答
可以哭但决不认输i
2楼-- · 2019-01-10 08:57

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.

查看更多
Melony?
3楼-- · 2019-01-10 09:00

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.

查看更多
登录 后发表回答