Fun 0.41.5
The programming language that makes You have fun
Loading...
Searching...
No Matches
socket_tcp_connect.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
22
24 /* Pops port, host; pushes fd (>0) or 0 */
25 Value portv = pop_value(vm);
26 Value hostv = pop_value(vm);
27 int fd = 0;
28#ifdef __unix__
29 if (hostv.type != VAL_STRING || portv.type != VAL_INT) {
30 fprintf(stderr, "Runtime type error: tcp_connect expects (string host, int port)\n");
33 push_value(vm, make_int(0));
34 break;
35 }
36 char *host = value_to_string_alloc(&hostv);
37 int port = (int)portv.i;
38 if (host) {
39 char portstr[16];
40 snprintf(portstr, sizeof(portstr), "%d", port);
41 struct addrinfo hints, *res = NULL, *rp;
42 memset(&hints, 0, sizeof(hints));
43 hints.ai_family = AF_UNSPEC;
44 hints.ai_socktype = SOCK_STREAM;
45 if (getaddrinfo(host, portstr, &hints, &res) == 0) {
46 for (rp = res; rp != NULL; rp = rp->ai_next) {
47 int s = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
48 if (s < 0) continue;
49 if (connect(s, rp->ai_addr, rp->ai_addrlen) == 0) {
50 fd = s;
51 break;
52 }
53 close(s);
54 }
55 if (res) freeaddrinfo(res);
56 }
57 free(host);
58 }
59#endif
62 push_value(vm, make_int(fd > 0 ? fd : 0));
63 break;
64}
int res
Definition and.c:34
@ OP_SOCK_TCP_CONNECT
Definition bytecode.h:222
free(vals)
uint32_t s
Definition rol.c:31
int fd
Definition serial_open.c:92
push_value(vm, make_int(fd > 0 ? fd :0))
Value hostv
free_value(portv)
Value portv
Tagged union representing a Fun value.
Definition value.h:68
char * value_to_string_alloc(const Value *v)
Allocate a printable C string for a Value.
Definition value.c:641
Value make_int(int64_t v)
Construct a Value representing a 64-bit integer.
Definition value.c:51
@ VAL_STRING
Definition value.h:53
@ VAL_INT
Definition value.h:51
#define fprintf
Definition vm.c:200