简体   繁体   English

套接字的地址族在结构和套接字创建中为何被提及?

[英]Address family of socket is mentioned in structure and socket creation why?

My doubt is over the code of lines in the socket program. 我的疑问是套接字程序中的行代码。 The family of address is specified in serv_addr.sin_family = AF_INET; 地址族在serv_addr.sin_family = AF_INET;指定serv_addr.sin_family = AF_INET; sockaddr_in structure, but then why should we mention the same in socket(AF_INET, SOCK_STREAM, 0); sockaddr_in结构,但是为什么我们要在socket(AF_INET, SOCK_STREAM, 0);提到相同的结构socket(AF_INET, SOCK_STREAM, 0); socket creation. 套接字创建。 What does the family address in two sentence mean? 两句话中的家庭住址是什么意思?

struct sockaddr_in serv_addr; 
listenfd = socket(AF_INET, SOCK_STREAM, 0);//here 

serv_addr.sin_family = AF_INET;//and here
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);

socket() creates a new socket. socket()创建一个新的套接字。 It needs to know what its address family is so it knows what kind of addresses it is allowed to work with, whether that be IPv4, IPv6, IPX, NetLink, etc. The address family dictates the layout and format for its address values. 它需要知道其地址族是什么,因此它知道允许使用哪种地址,即IPv4,IPv6,IPX,NetLink等。地址族规定了其地址值的布局和格式。 For instance, AF_INET only allows IPv4 addresses, whereas AF_INET6 allows IPv6 addresses (and IPv4 addresses if the socket is set to dual-stack mode on platforms that support that feature). 例如, AF_INET仅允许IPv4地址,而AF_INET6允许IPv6地址(如果套接字在支持该功能的平台上设置为双栈模式,则为IPv4地址)。

Every sockaddr_... structure has a family field. 每个sockaddr_...结构都有一个家庭字段。 sockaddr_... structures can be passed around to various functions, which need to know what type of address they are receiving as input, and can specify what type of address they are returning as output. sockaddr_...结构可以传递给各种函数,这些函数需要知道它们作为输入接收的地址的类型,并可以指定它们作为输出返回的地址的类型。

The sockaddr_in structure is specific to IPv4 addresses only, where its sin_addr field specifies the IPv4 address as a 32bit integer in network byte order. sockaddr_in结构仅特定于IPv4地址,其中它的sin_addr字段将IPv4地址指定为网络字节顺序的32位整数。 The same is not true of other sockaddr_... structures. 其他sockaddr_...结构则不是这样。

There is a special sockaddr_storage structure that is typically used when writing code that works with multiple addresses families, especially when calling functions that can accept multiple sockaddr_... types. 有一个特殊的sockaddr_storage结构,通常在编写适用于多个地址族的代码时使用,特别是在调用可以接受多个sockaddr_...类型的函数时。

So it is important not only for the socket to be told what its address family is, but it is also important for individual addresses to specify their own types as well. 因此,不仅要告知套接字其地址族是重要的,而且对于单个地址也要指定其自己的类型也很重要。 Typically, these values will match each other (except in the case of dual-stack sockets). 通常,这些值将彼此匹配(双堆栈插槽除外)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM