Skip to content

Commit bc586e3

Browse files
committed
WiFi server listens on IPv6 (in addition to IPv4).
1 parent 844bc2e commit bc586e3

File tree

1 file changed

+61
-10
lines changed

1 file changed

+61
-10
lines changed

Diff for: libraries/WiFi/src/WiFiServer.cpp

+61-10
Original file line numberDiff line numberDiff line change
@@ -76,17 +76,68 @@ void WiFiServer::begin(uint16_t port, int enable){
7676
if(port){
7777
_port = port;
7878
}
79-
struct sockaddr_in server;
80-
sockfd = socket(AF_INET , SOCK_STREAM, 0);
81-
if (sockfd < 0)
79+
int n, ret;
80+
struct addrinfo hints, *addr_list, *cur;
81+
memset(&hints, 0, sizeof(hints));
82+
hints.ai_family = AF_UNSPEC;
83+
hints.ai_socktype = SOCK_STREAM;
84+
hints.ai_protocol = IPPROTO_TCP;
85+
if (getaddrinfo("::", inet_ntoa(_port), &hints, &addr_list) != 0)
8286
return;
83-
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int));
84-
server.sin_family = AF_INET;
85-
server.sin_addr.s_addr = _addr;
86-
server.sin_port = htons(_port);
87-
if(bind(sockfd, (struct sockaddr *)&server, sizeof(server)) < 0)
88-
return;
89-
if(listen(sockfd , _max_clients) < 0)
87+
/* Try the sockaddrs until a binding succeeds */
88+
ret = 1; // unknown host
89+
for (cur = addr_list; cur != NULL; cur = cur->ai_next)
90+
{
91+
sockfd = (int) socket(cur->ai_family, cur->ai_socktype, cur->ai_protocol);
92+
if (sockfd < 0)
93+
{
94+
//ret = 2; // socket failed
95+
continue;
96+
}
97+
98+
n = 1;
99+
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char *) &n,
100+
sizeof(n)) != 0)
101+
{
102+
#ifdef ESP_IDF_VERSION_MAJOR
103+
lwip_close(sockfd);
104+
#else
105+
lwip_close_r(sockfd);
106+
#endif
107+
//ret = 3; // setsockopt failed
108+
continue;
109+
}
110+
111+
if (bind(sockfd, cur->ai_addr, cur->ai_addrlen) != 0)
112+
{
113+
#ifdef ESP_IDF_VERSION_MAJOR
114+
lwip_close(sockfd);
115+
#else
116+
lwip_close_r(sockfd);
117+
#endif
118+
//ret = 4; // bind failed
119+
continue;
120+
}
121+
122+
if (listen(sockfd, _max_clients) != 0)
123+
{
124+
#ifdef ESP_IDF_VERSION_MAJOR
125+
lwip_close(sockfd);
126+
#else
127+
lwip_close_r(sockfd);
128+
#endif
129+
//ret = 5; // listen failed
130+
continue;
131+
}
132+
133+
/* Bind was successful */
134+
ret = 0;
135+
break;
136+
}
137+
138+
freeaddrinfo(addr_list);
139+
140+
if (ret != 0)
90141
return;
91142
fcntl(sockfd, F_SETFL, O_NONBLOCK);
92143
_listening = true;

0 commit comments

Comments
 (0)