Fun 0.41.5
The programming language that makes You have fun
Loading...
Searching...
No Matches
socket_tcp_listen.c
Go to the documentation of this file.
1/*
2 * This file is part of the Fun programming language.
3 * https://fun-lang.xyz/
4 *
5 * Copyright 2025 Johannes Findeisen <you@hanez.org>
6 * Licensed under the terms of the Apache-2.0 license.
7 * https://opensource.org/license/apache-2-0
8 */
9
20
22 /* Pops backlog, port; pushes listen fd (>0) or 0 */
23 Value backlogv = pop_value(vm);
24 Value portv = pop_value(vm);
25 int fd = 0;
26#ifdef __unix__
27 if (portv.type != VAL_INT || backlogv.type != VAL_INT) {
28 fprintf(stderr, "Runtime type error: tcp_listen expects (int port, int backlog)\n");
29 free_value(backlogv);
31 push_value(vm, make_int(0));
32 break;
33 }
34 int port = (int)portv.i;
35 int backlog = (int)backlogv.i;
36 int s = socket(AF_INET, SOCK_STREAM, 0);
37 if (s >= 0) {
38 int yes = 1;
39 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
40 struct sockaddr_in addr;
41 memset(&addr, 0, sizeof(addr));
42 addr.sin_family = AF_INET;
43 addr.sin_addr.s_addr = htonl(INADDR_ANY);
44 addr.sin_port = htons((uint16_t)port);
45 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) == 0) {
46 if (listen(s, backlog > 0 ? backlog : 1) == 0) {
47 fd = s;
48 } else {
49 close(s);
50 }
51 } else {
52 close(s);
53 }
54 }
55#else
56 (void)fd;
57#endif
58 free_value(backlogv);
60 push_value(vm, make_int(fd > 0 ? fd : 0));
61 break;
62}
@ OP_SOCK_TCP_LISTEN
Definition bytecode.h:220
uint32_t s
Definition rol.c:31
int fd
Definition serial_open.c:92
Value portv
free_value(backlogv)
push_value(vm, make_int(fd > 0 ? fd :0))
Tagged union representing a Fun value.
Definition value.h:68
int64_t i
Definition value.h:71
ValueType type
Definition value.h:69
Value make_int(int64_t v)
Construct a Value representing a 64-bit integer.
Definition value.c:51
@ VAL_INT
Definition value.h:51
#define fprintf
Definition vm.c:200