Skip to content

Commit 84f6f6f

Browse files
committed
wasi-sockets: implement getservbyname & getservbyport
1 parent 6872c8e commit 84f6f6f

File tree

1 file changed

+35
-4
lines changed

1 file changed

+35
-4
lines changed

libc-bottom-half/sources/netdb.c

+35-4
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77

88
_Thread_local int h_errno = 0;
99

10+
static struct servent global_serv = { 0 };
11+
1012
static int map_error(ip_name_lookup_error_code_t error)
1113
{
1214
switch (error) {
@@ -137,6 +139,29 @@ static int add_addr(ip_name_lookup_option_ip_address_t address,
137139
return 0;
138140
}
139141

142+
static bool set_global_serv_entry(const service_entry_t *entry, const char *proto) {
143+
if (!entry) {
144+
return false; // Service not found
145+
}
146+
147+
global_serv.s_name = entry->s_name;
148+
global_serv.s_port = htons(entry->port);
149+
global_serv.s_aliases = NULL;
150+
151+
// If proto is NULL then any protocol is matched
152+
if ((!proto || strcmp(proto, "tcp") == 0) && entry->protocol & SERVICE_PROTOCOL_TCP) {
153+
global_serv.s_proto = "tcp";
154+
}
155+
else if ((!proto || strcmp(proto, "udp") == 0) && entry->protocol & SERVICE_PROTOCOL_UDP) {
156+
global_serv.s_proto = "udp";
157+
}
158+
else {
159+
return false; // Protocol not supported
160+
}
161+
162+
return true;
163+
}
164+
140165
int getaddrinfo(const char *restrict host, const char *restrict serv,
141166
const struct addrinfo *restrict hint,
142167
struct addrinfo **restrict res)
@@ -249,14 +274,20 @@ const char *hstrerror(int err)
249274

250275
struct servent *getservbyname(const char *name, const char *proto)
251276
{
252-
// TODO wasi-sockets
253-
return NULL;
277+
const service_entry_t *entry = __wasi_sockets_utils__get_service_entry_by_name(name);
278+
if (!set_global_serv_entry(entry, proto)) {
279+
return NULL;
280+
}
281+
return &global_serv;
254282
}
255283

256284
struct servent *getservbyport(int port, const char *proto)
257285
{
258-
// TODO wasi-sockets
259-
return NULL;
286+
const service_entry_t *entry = __wasi_sockets_utils__get_service_entry_by_port(htons(port));
287+
if (!set_global_serv_entry(entry, proto)) {
288+
return NULL;
289+
}
290+
return &global_serv;
260291
}
261292

262293
struct protoent *getprotobyname(const char *name)

0 commit comments

Comments
 (0)