Skip to content

Instantly share code, notes, and snippets.

@tetsu-koba
Last active December 24, 2022 06:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tetsu-koba/2256beb240ab889b482a975e613fb2c1 to your computer and use it in GitHub Desktop.
Save tetsu-koba/2256beb240ab889b482a975e613fb2c1 to your computer and use it in GitHub Desktop.
Zig library example
#include <stdio.h>
#include <time.h>
#include "udp_get_time.h"
int main()
{
const char *ipaddr = "127.0.0.1";
time_t t = udp_get_time(ipaddr);
puts(ctime(&t));
}
CC = zig cc
all: main
main: main.o libudp_time_lib.a
$(CC) -o $@ $^
libudp_time_lib.a: udp_time_lib.zig
zig build-lib -lc -O ReleaseSmall $<
main.o: main.c udp_get_time.h
clean:
rm -rf *.o *.a main
#ifndef _UDP_GET_TIME_H
#define _UDP_GET_TIME_H 1
#include <time.h>
extern time_t udp_get_time(const char *ipaddr);
#endif /* _UDP_GET_TIME_H */
const std = @import("std");
const os = std.os;
const log = std.log;
const time = std.time;
const c = @cImport(@cInclude("time.h"));
const UDP_PAYLOADSIZE = 65507;
const TIMESERVER_PORT = 37;
const UNIX_TIME_BASE = 2_208_988_800;
fn queryTime(ipaddr: []const u8, verbose:bool) !u32 {
var buf: [UDP_PAYLOADSIZE]u8 = .{};
const sockfd = try os.socket(os.AF.INET, os.SOCK.DGRAM | os.SOCK.CLOEXEC, 0);
defer os.closeSocket(sockfd);
const addr = try std.net.Address.resolveIp(ipaddr, TIMESERVER_PORT);
try os.connect(sockfd, &addr.any, addr.getOsSockLen());
if (0 != try os.send(sockfd, "", 0)) unreachable; // send empty data
if (4 != try os.recv(sockfd, &buf, 0)) unreachable;
const t = std.mem.readIntBig(u32, buf[0..4]);
if (verbose) {
log.info("{d}: t={d}", .{time.milliTimestamp(), t});
}
// timeserver returns the number of seconds since 00:00 (midnight) 1 January 1900 GMT
return t - UNIX_TIME_BASE;
}
export fn udp_get_time(c_ipaddr: [*c]const u8) c.time_t {
const ipaddr = std.mem.sliceTo(c_ipaddr, 0);
return queryTime(ipaddr, false) catch -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment