Last active
April 15, 2024 14:37
-
-
Save 0x4c756e61/060d7a2fde76fe24c7d14d48bf02752e to your computer and use it in GitHub Desktop.
C socket programming in Zig
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// compile with zig build-exe srv.c.zig -lc (zig @master) | |
const c = @cImport({ | |
@cInclude("sys/socket.h"); | |
@cInclude("sys/types.h"); | |
@cInclude("arpa/inet.h"); | |
@cInclude("unistd.h"); | |
@cInclude("netinet/in.h"); | |
}); | |
const std = @import("std"); | |
pub fn main() !void { | |
const socket: c_int = c.socket(c.AF_INET, c.SOCK_STREAM, 0); | |
defer _ = c.close(socket); | |
const saddr: c.sockaddr_in = c.sockaddr_in{ | |
.sin_family = c.AF_INET, | |
.sin_port = c.htons(5353), | |
.sin_addr = c.struct_in_addr{ .s_addr = c.inet_addr("127.0.0.1") }, | |
}; | |
if (c.bind(socket, @ptrCast(&saddr), @sizeOf(c.sockaddr)) < 0) { | |
std.debug.print("Could not bind to specified address and port", .{}); | |
return; | |
} | |
std.debug.print("Listening\n", .{}); | |
if (c.listen(socket, 1) < 0) { | |
std.debug.print("Couldn't listen on specified address and port !\n", .{}); | |
} | |
var caddr: c.sockaddr_in = std.mem.zeroes(c.sockaddr_in); | |
var csize: c.socklen_t = std.mem.zeroes(c.socklen_t); | |
const csocket = c.accept(socket, @ptrCast(&caddr), &csize); | |
defer _ = c.close(csocket); | |
if (csocket < 0) { | |
std.debug.print("Accepting client failed!\n", .{}); | |
return; | |
} | |
_ = c.send(csocket, "heyyy", 5, 0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I created this to test zig's interoperability with C, and because my teacher wanted me to "use c primitives"