Do networking?
Work-in-progress page, just wanted to capture some trickiness Jack came across.
- In
net_bind()
,IPPROTO_TCP
as the third parameter gives the cryptic error -81, which is not really defined anywhere. This really needs to beIPPROTO_IP
instead. - Get your port number right!
Example
int32_t listen_tcp(uint16_t port)
{
// Create server socket.
int32_t sock = net_socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
if (sock == INVALID_SOCKET)
return -1;
struct sockaddr_in server;
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(port);
server.sin_addr.s_addr = INADDR_ANY;
// Bind server socket.
int32_t ret = net_bind(sock, (struct sockaddr *)&server, sizeof(server));
if (ret < 0)
return ret;
// Listen on server socket.
ret = net_listen(sock, 10);
if (ret < 0)
return ret;
// Create client socket.
struct sockaddr_in client;
memset(&server, 0, sizeof(server));
uint32_t client_len = sizeof(client);
// Create receive buffer.
char buffer[1024];
while (true)
{
printf("\x1b[%d;%dH", 4, 0);
printf("Waiting for data...");
int32_t csock = net_accept(sock, (struct sockaddr *)&client, &client_len);
if (csock < 0)
return ret;
// Reset buffer and receive contents.
memset(buffer, 0, 1024);
int32_t bytes = net_recv(csock, buffer, 1024, 0);
printf("\x1b[%d;%dH", 5, 0);
printf("Received %d bytes.", bytes);
// Print buffer to screen.
printf("\x1b[%d;%dH", 6, 0);
printf(buffer);
net_close(csock);
}
return 1;
}
No Comments