我当时正在编写一个winsock2程序,而MSDN上的一行代码吸引了我的眼球:
ConnectSocket=socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);为什么指针被用来引用结构而不是直接引用点运算符的结构?
编辑:参见这里的代码:为客户端创建套接字
发布于 2016-10-15 02:58:06
操作时,.运算符用于访问对象的成员
->运算符用于在上操作时访问对象的成员--指向对象的指针:
Type obj;
Type *ptr = &obj;
ptr->member->运算符只是将*和.运算符结合在一起使用的一种更干净的方法:
Type obj;
Type *ptr = &obj;
(*ptr).member在这种情况下,由于ptr是一个指针,所以可以使用->或*.访问其成员。
在链接示例中,ptr之所以是指针,是因为代码使用的是getaddrinfo(),它返回动态分配的addrinfo结构链接列表,其中ptr是指向列表中特定项的指针。
MSDN示例只访问列表中的第一项,但通常循环遍历整个列表,因为getaddrinfo()可以返回多个地址。您需要使用指针循环列表,例如:
#define DEFAULT_PORT "27015"
int main(int argc, char** argv)
{
SOCKET ConnectSocket = INVALID_SOCKET;
struct addrinfo *result = NULL,
*ptr = NULL,
hints;
int iResult;
WSADATA wsa;
iResult = WSAStartup(MAKEWORD(2, 0), &wsa);
if (iResult != 0) {
printf("WSAStartup failed: %d\n", iResult);
return 1;
}
ZeroMemory( &hints, sizeof(hints) );
hints.ai_family = AF_UNSPEC; // allows IPv4 and IPv6 addresses
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// Resolve the server address and port
iResult = getaddrinfo(argv[1], DEFAULT_PORT, &hints, &result);
if (iResult != 0) {
printf("getaddrinfo failed: %d\n", iResult);
WSACleanup();
return 1;
}
// Attempt to connect to each address returned by
// the call to getaddrinfo until one succeeds
for(ptr = result; ptr != NULL; ptr = ptr->ai_next)
{
// Create a SOCKET for connecting to server
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
if (ConnectSocket == INVALID_SOCKET) {
printf("Error at socket(): %ld\n", WSAGetLastError());
continue;
}
// connect to server
iResult = connect(ConnectSocket, ptr->ai_addr, ptr->ai_addrlen);
if (iResult == 0) {
printf("Connected!\n");
break;
}
printf("Unable to connect: %ld\n", WSAGetLastError());
// Destroy the SOCKET before trying the next address
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
}
freeaddrinfo(result);
if (ConnectSocket != INVALID_SOCKET) {
// use ConnectSocket as needed...
closesocket(ConnectSocket);
}
WSACleaup();
return 0;
}https://stackoverflow.com/questions/40054309
复制相似问题