Last active
November 18, 2020 21:14
-
-
Save nektro/e76b2642ba43d098aee7 to your computer and use it in GitHub Desktop.
Open a TCP socket and create a handmade HTTP 1.1 GET request
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
<?php | |
/** | |
* Connect to an HTTP server and echo the response | |
*/ | |
$host = 'localhost'; | |
$port = 80; | |
$fp = fsockopen($host, $port, $errno, $errstr, 30); | |
if (!$fp) { | |
echo "$errstr ($errno)<br />\n"; | |
} | |
else { | |
$out = "GET / HTTP/1.1\r\n"; | |
$out .= "Host: $host:$port\r\n"; | |
$out .= "Connection: Close\r\n\r\n"; | |
fwrite($fp, $out); | |
while (!feof($fp)) { | |
echo fgets($fp, 128); | |
} | |
fclose($fp); | |
} |
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
const std = @import("std"); | |
pub fn main() !void { | |
const gpa = std.heap.c_allocator; | |
const host = "example.com"; | |
const port = 80; | |
const sock = try std.net.tcpConnectToHost(gpa, host, port); | |
const w = sock.writer(); | |
try w.print("GET / HTTP/1.1\r\n", .{}); | |
try w.print("Host: {}:{}\r\n", .{host, port}); | |
try w.print("Connection: Close\r\n\r\n", .{}); | |
const stdout = std.io.getStdOut().writer(); | |
const r = sock.reader(); | |
var buf: [128]u8 = undefined; | |
while (true) { | |
const len = try r.read(&buf); | |
if (!(len > 0)) { | |
break; | |
} | |
try stdout.writeAll(buf[0..len]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment