9.3. connect()
#include <sys/types.h>
#include <sys/socket.h>
int connect(int sockfd, const struct sockaddr *serv_addr,
socklen_t addrlen);// 连接到 www.example.com 的 port 80(http)
struct addrinfo hints, *res;
int sockfd;
// 首先,使用 getaddrinfo() 取得地址数据:
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; // use IPv4 or IPv6, whichever
hints.ai_socktype = SOCK_STREAM;
// 我们可以在下一行用 "http" 取代 "80":
getaddrinfo("www.example.com", "http", &hints, &res);
// 建立一个 socket:
sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
// 将 socket 连接到我们在 getaddrinfo() 里指定的 address 与 port:
connect(sockfd, res->ai_addr, res->ai_addrlen);Last updated