wasm-micro-runtime/samples/socket-api/wasm-src/socket_utils.h
Wenyong Huang 78b5c5b484
Merge dev/socket into main (#1393)
Implement more socket APIs, refer to #1336 and below PRs:
- Implement wasi_addr_resolve function (#1319)
- Fix socket-api byte order issue when host/network order are the same (#1327)
- Enhance sock_addr_local syscall (#1320)
- Implement sock_addr_remote syscall (#1360)
- Add support for IPv6 in WAMR (#1411)
- Implement ns lookup allowlist (#1420)
- Implement sock_send_to and sock_recv_from system calls (#1457)
- Added http downloader and multicast socket options (#1467)
- Fix `bind()` calls to receive the correct size of `sockaddr` structure (#1490)
- Assert on correct parameters (#1505)
- Copy only received bytes from socket recv buffer into the app buffer (#1497)

Co-authored-by: Marcin Kolny <mkolny@amazon.com>
Co-authored-by: Marcin Kolny <marcin.kolny@gmail.com>
Co-authored-by: Callum Macmillan <callumimacmillan@gmail.com>
2022-09-22 21:46:14 +08:00

48 lines
1.1 KiB
C

/*
* Copyright (C) 2022 Amazon.com Inc. or its affiliates. All rights reserved.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*/
#ifndef TCP_UTILS_H
#define TCP_UTILS_H
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
int
sockaddr_to_string(struct sockaddr *addr, char *str, size_t len)
{
uint16_t port;
char ip_string[64];
void *addr_buf;
int ret;
switch (addr->sa_family) {
case AF_INET:
{
struct sockaddr_in *addr_in = (struct sockaddr_in *)addr;
port = addr_in->sin_port;
addr_buf = &addr_in->sin_addr;
break;
}
case AF_INET6:
{
struct sockaddr_in6 *addr_in6 = (struct sockaddr_in6 *)addr;
port = addr_in6->sin6_port;
addr_buf = &addr_in6->sin6_addr;
break;
}
default:
return -1;
}
inet_ntop(addr->sa_family, addr_buf, ip_string,
sizeof(ip_string) / sizeof(ip_string[0]));
ret = snprintf(str, len, "%s:%d", ip_string, ntohs(port));
return ret > 0 && (size_t)ret < len ? 0 : -1;
}
#endif /* TCP_UTILS_H */