diff options
| author | Jonathan Marler <johnnymarler@gmail.com> | 2019-10-27 21:15:06 -0600 |
|---|---|---|
| committer | Jonathan Marler <johnnymarler@gmail.com> | 2019-10-29 00:27:45 -0600 |
| commit | 4e0c2ed443a0c13030decf8a9d53aff28f415005 (patch) | |
| tree | 5abd2f2768dd4e98ffd187fa9eef156c29e01446 /lib/std/net.zig | |
| parent | 67058b9b7089446e16eee3c03ab3f8f9a5d13529 (diff) | |
| download | zig-4e0c2ed443a0c13030decf8a9d53aff28f415005.tar.gz zig-4e0c2ed443a0c13030decf8a9d53aff28f415005.zip | |
Add tests for ip address formatting
Diffstat (limited to 'lib/std/net.zig')
| -rw-r--r-- | lib/std/net.zig | 48 |
1 files changed, 40 insertions, 8 deletions
diff --git a/lib/std/net.zig b/lib/std/net.zig index 2ca0e1fc26..61f1c80036 100644 --- a/lib/std/net.zig +++ b/lib/std/net.zig @@ -22,16 +22,31 @@ pub const Address = struct { os_addr: OsAddress, pub fn initIp4(ip4: u32, _port: u16) Address { - return Address{ - .os_addr = os.sockaddr{ - .in = os.sockaddr_in{ - .family = os.AF_INET, - .port = mem.nativeToBig(u16, _port), - .addr = ip4, - .zero = [_]u8{0} ** 8, + switch (builtin.os) { + .macosx, .ios, .watchos, .tvos, + .freebsd, .netbsd => return Address{ + .os_addr = os.sockaddr{ + .in = os.sockaddr_in{ + .len = @sizeOf(os.sockaddr_in), + .family = os.AF_INET, + .port = mem.nativeToBig(u16, _port), + .addr = ip4, + .zero = [_]u8{0} ** 8, + }, }, }, - }; + .linux => return Address{ + .os_addr = os.sockaddr{ + .in = os.sockaddr_in{ + .family = os.AF_INET, + .port = mem.nativeToBig(u16, _port), + .addr = ip4, + .zero = [_]u8{0} ** 8, + }, + }, + }, + else => @compileError("Address.initIp4 not implemented for this platform"), + } } pub fn initIp6(ip6: Ip6Addr, _port: u16) Address { @@ -286,6 +301,23 @@ test "std.net.parseIp6" { std.testing.expect(mem.eql(u8, "[ff01::fb]:80", printed)); } +fn testIp4s(ips: []const []const u8) void { + var buffer : [18]u8 = undefined; + for (ips) |ip| { + var addr = Address.initIp4(parseIp4(ip) catch unreachable, 0); + var newIp = std.fmt.bufPrint(buffer[0..], "{}", addr) catch unreachable; + std.testing.expect(std.mem.eql(u8, ip, newIp[0..newIp.len - 2])); + } +} + +test "std.net.ip4s" { + testIp4s(([_][]const u8 { + "0.0.0.0" , + "255.255.255.255" , + "1.2.3.4", + "123.255.0.91", + })[0..]); +} pub fn connectUnixSocket(path: []const u8) !fs.File { const opt_non_block = if (std.event.Loop.instance != null) os.SOCK_NONBLOCK else 0; const sockfd = try os.socket( |
