[英]Socket connect() function explanation in C++/ Reference operator and Pointers
I'm new to programming and would like a better understanding of this socket function connect(). 我是编程的新手,希望对此套接字函数connect()有更好的了解。 I've read many descriptions but I couldn't understand this syntax:
我已经阅读了许多说明,但是我不明白此语法:
int connect(int sockfd, const struct sockaddr *addr,socklen_t addrlen)
Description: The addr argument is a pointer to a structure specifying the address to which this socket is to be bound. 说明:addr参数是一个指向结构的指针,该结构指定此套接字将绑定到的地址。
This is part of my studying code: 这是我学习代码的一部分:
connect(socket_desc ,( struct sockaddr *) &server , sizeof(server)) < 0)
Can anyone explain why there is a structure in parentheses with a pointer operator and the reference operator after it? 谁能解释为什么在括号中有一个指针运算符和引用运算符之后的结构?
The ( struct sockaddr *) &server
part of that line can be described in English as: 该行的
( struct sockaddr *) &server
部分可以用英语描述为:
Take the address of the object server
, and treat that memory address (or pointer) as if it were a pointer to a sockaddr
object. 获取对象
server
的地址,并将该内存地址(或指针)视为指向sockaddr
对象的指针。
The &
operator, at least in this context, is taking the memory address of the identifier that follows. 至少在这种情况下,
&
运算符正在获取后面标识符的存储地址。 An expression that is preceded by (type)
is 'cast' to that type. 以
(type)
开头的表达式被“投射”到该类型。 In C, that is the only form of type casting. 在C语言中,这是类型转换的唯一形式。 C++ inherits that functionality, but is discouraged in most C++ code in favor of the other casting operations (static_cast, dynamic_cast, const_cast, reinterpret_cast).
C ++继承了该功能,但在大多数C ++代码中不建议使用其他强制转换操作(static_cast,dynamic_cast,const_cast,reinterpret_cast)。
Can anyone explain why there is a structure in parentheses with a pointer operator and the reference operator after it?
谁能解释为什么在括号中有一个指针运算符和引用运算符之后的结构?
The parenthesis are being used for a type cast , and the ampersand is the address-of operator . 括号用于类型转换 ,而“&”号是地址运算符 。 The code is obtaining the memory address of a struct variable, likely a
sockaddr_in
or sockaddr_in6
but could be any sockaddr
-compatible struct, and then type-casting that memory address to a sockaddr
pointer. 该代码获取结构变量(可能是
sockaddr_in
或sockaddr_in6
但可以是任何sockaddr
兼容的结构)的内存地址,然后将该内存地址类型转换为sockaddr
指针。
Sockets support many different types of addressing schemes, and there is a different sockaddr_...
struct type defined for each of them. 套接字支持许多不同类型的寻址方案,并且为每种套接字定义了不同的
sockaddr_...
结构类型。 But the socket API functions that deal with addresses only accept sockaddr*
parameters, so type-casting is needed. 但是处理地址的套接字API函数仅接受
sockaddr*
参数,因此需要类型转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.