2
0

socket.zig 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. const std = @import("std");
  2. const net = std.net;
  3. const posix = std.posix;
  4. pub fn init(port: u16) !posix.socket_t {
  5. const address = try std.net.Address.parseIp("0.0.0.0", port);
  6. const tpe: u32 = posix.SOCK.STREAM;
  7. const protocol = posix.IPPROTO.TCP;
  8. const listener = try posix.socket(address.any.family, tpe, protocol);
  9. try posix.setsockopt(listener, posix.SOL.SOCKET, posix.SO.REUSEADDR, &std.mem.toBytes(@as(c_int, 1)));
  10. try posix.bind(listener, &address.any, address.getOsSockLen());
  11. try posix.listen(listener, 128);
  12. return listener;
  13. }
  14. pub fn readUntilCR(conn: posix.socket_t, buf: []u8) !usize {
  15. var total: usize = 0;
  16. while (total < buf.len) {
  17. const n = try posix.read(conn, buf[total..]);
  18. if (n == 0) {
  19. return if (total > 0) total else error.ConnectionClosed;
  20. }
  21. if (std.mem.indexOfScalar(u8, buf[total .. total + n], '\r')) |offset| {
  22. return total + offset;
  23. }
  24. total += n;
  25. }
  26. return total;
  27. }
  28. pub fn read(conn: posix.socket_t, buf: []u8) !usize {
  29. var pos: usize = 0;
  30. while (pos < buf.len) {
  31. const n = try posix.read(conn, buf[pos..]);
  32. if (n == 0) {
  33. return pos;
  34. }
  35. pos += n;
  36. }
  37. return pos;
  38. }
  39. pub fn write(conn: posix.socket_t, msg: []const u8) !void {
  40. const written = try posix.write(conn, msg);
  41. if (written != msg.len) {
  42. return error.PartialWrite;
  43. }
  44. }