Need help with writing and reading into/from a socket


#1

As an excercise in learning little, I’ve decided to write a simple script that writes to a socket and reads the answer.

Now the problem is, it behaves in a way I don’t get: both fprintf() and write() only actually write the data when read() finishes. Even though read() is after write().

Here’s the code:

#!/usr/bin/env L
/* vim: ft=c */

int main(int argc, string argv[]) {
	string   host    = argv[1];
	int      portn   = (int)argv[2];
	string   query   = "Hello";
	string   netout;
	FILE     netfd;

	try {
		netfd = socket(host, portn);
	} catch {
		fprintf(stderr, "ERROR opening socket to %s:%d\n", host, portn);
		exit(1);
	}

	fprintf(netfd, "%s\n", query);
	read(netfd, &netout, -1);

	return(0);
}

And yes, write() behaves the same.

UPD: It will also not write anything if the server doesn’t send an EOF.


#2

Try adding a flush(netfd) after the fprintf() and before the read().
The filehandle is buffered and so it doesn’t actually call the system’s write() until the buffers are flushed.
(Which happens at the end currently)

Also you probably want to add a close(netfd) at the end and be checking the return values from most of those calls.


#3

Oh. Yes, flushing it works, thanks.

As for checking values: of course it will check everything eventually :slight_smile:


#4

Also more idiomatic C would be written like this:

        if (!(netfd = socket(host, portn)) {
		fprintf(stderr, "ERROR opening socket to %s:%d\n", host, portn);
		exit(1);
	}

I haven’t tested this, but pretty sure it will work. Despite doing support for Little at the moment, I haven’t actually used it much. However I am a C programmer and Little is designed to be obvious to C programmers.


#5

That way it crashes with an error:

 . fbt@twilight /tmp/stuff > ./netcat.l fleshless.org 801
couldn't open socket: connection refused
    while executing
"!( netfd = socket( host, portn ))"

if we failed to establish a connection.