Skip to content

Instantly share code, notes, and snippets.

@tetsu-koba
Last active December 21, 2022 02:06
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/ee182b60ca5f8d44f5c4657903d31593 to your computer and use it in GitHub Desktop.
Save tetsu-koba/ee182b60ca5f8d44f5c4657903d31593 to your computer and use it in GitHub Desktop.
UDP client library for Zig
UDP client library for Zig
const std = @import("std");
const os = std.os;
const net = std.net;
pub fn udpConnectToAddress(address: net.Address) !net.Stream {
const sockfd = try os.socket(os.AF.INET, os.SOCK.DGRAM | os.SOCK.CLOEXEC, 0);
errdefer os.closeSocket(sockfd);
try os.connect(sockfd, &address.any, address.getOsSockLen());
return net.Stream{ .handle = sockfd };
}
const std = @import("std");
const udp = @import("udp.zig");
const os = std.os;
const log = std.log;
const time = std.time;
const net = std.net;
const UDP_PAYLOADSIZE = 65507;
fn helloToServer(adr: []const u8, port: u16, verbose:bool) !void {
const a = try net.Address.resolveIp(adr, port);
var s = try udp.udpConnectToAddress(a);
defer s.close();
if (verbose) {
log.info("{d}:Connected.", .{time.milliTimestamp()});
}
const bytes_write = try s.write("Hello from client.");
if (verbose) {
log.info("{d}:bytes_write={d}", .{time.milliTimestamp(),bytes_write});
}
var buf: [UDP_PAYLOADSIZE]u8 = .{};
const bytes_read = try s.read(&buf);
if (verbose) {
log.info("{d}:Got message [{s}].", .{time.milliTimestamp(),buf[0..bytes_read]});
}
}
pub fn main() !void {
// TODO: get parameters from command line options
const verbose = true;
const adr = "127.0.0.1";
const port = 7200;
try helloToServer(adr, port, verbose);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment