Code: Select all
// 1、定义一个hints结构体,用来设置函数的getaddrinfo()的使用方式
const struct addrinfo hints = {
.ai_family = AF_INET, /* 指定返回地址的协议簇,AF_INET(IPv4)、AF_INET6(IPv6)、AF_UNSPEC(IPv4 and IPv6)*/
.ai_socktype = SOCK_STREAM, /* 设定返回地址的socket类型,流式套接字 */
};
while (1) {
// 2、使用getaddrinfo()开始解析,定义一个struct addrinfo结构体指针,用来获取解析结果
struct addrinfo *result;
int err;
int sock;
err = getaddrinfo("www.baidu.com", "80", &hints, &result);
if(err != 0) /* 返回值不为0,函数执行失败*/
{
printf("getaddrinfo err: %d \n",err);
}
// 3、将获取到的信息打印出来
char buf[100]; /* 用来存储IP地址字符串 */
struct sockaddr_in *ipv4 = NULL; /* IPv4地址结构体指针 */
if(result->ai_family == AF_INET)
{
ipv4 = (struct sockaddr_in *)result->ai_addr;
inet_ntop(result->ai_family, &ipv4->sin_addr, buf, sizeof(buf));
printf("[IPv4]%s [port]%d \n",buf,ntohs(ipv4->sin_port));
sock = socket(AF_INET, SOCK_STREAM, ip_protocol);
if (sock < 0) {
ESP_LOGE(TAG, "Unable to create socket: errno %d", errno);
break;
}
ESP_LOGI(TAG, "Socket created, connecting to %s:%d", buf,ntohs(ipv4->sin_port));
err = connect(sock, (struct sockaddr *)&ipv4, sizeof(struct sockaddr_in));
}
else
{
printf("got IPv4 err !!!\n");
}
if (err != 0) {
ESP_LOGE(TAG, "Socket unable to connect: errno %d", errno); //程序执行到此处,log errno 22
break;
}
ESP_LOGI(TAG, "Successfully connected");