pete > courses > CS 315 Fall 26 > lecture 17: networking API
Lecture 17: networking API
Goals
- listen for incoming TCP connections; make a TCP connection; and transmit and receive data via TCP
before getting to the code, I’d like to review the high-level steps that happen to make a connection happen
here is the complete version of the picture we saw a couple days ago:
Process X Process Y
ask kernel for socket | |
bind socket to port | |
set socket to listen | |
| | ask kernel for socket
| | use DNS to get server IP
| | tell socket to connect
| connection request |
| <-------------------- |
receive request | |
create connection | |
send acknowledgement | acknowledgement |
| --------------------> | receive acknowledgement
| | connection is created
after this sequence of events has finished, the both processes can send data, receive data, or close the connection
the precise data we send and receive will be determined by the purpose for which we intend to use the connection (more on that in a moment)
let’s look at code
the classic simple example is called an "echo server" and corresponding client
the idea behind the server is that it allows clients to connect, it receives data from them, and it sends back to the client whatever it received
the client is even dumber: once it has connected to the server, it reads from the console and sends that data to the server, then it prints whatever the server sent back
Makefile for today
one warning: this API was designed before "everything" was standardized around IP, so there are some corners to it that seem a bit verbose
since it’s dumber, let’s start with the client: echo-client.c
this file contains INSUFFICIENT ERROR CHECKING
I left some in because it will help identify bad inputs when I’m running it
but when you write your own networking code, you will assiduously check return values
starts by including lots of header files, defining a buffer size because we’ll need a buffer later, and then declaring a bunch of variables in main
we’re getting the name of the machine to connect to, as well as the port on that machine, from the command-line:
dest_hostname = argv[1]; dest_port = argv[2];
the first real thing we do is create the socket, which is the communication endpoint, using the socket(2) system call
conn_fd = socket(PF_INET, SOCK_STREAM, 0);
PF_INET tells the kernel we’re going to be using the socket to perform Internet communications (because when the API was designed, there were other protocol families one might want to use)
SOCK_STREAM tells the kernel we want it to use TCP, which is the protocol that adds guaranteed in-order delivery of data on top of (unreliable) IP
as the comment says, client processes usually don’t bind their sockets to a port
that said, the connection will have a port assigned to it
(remember that a connection is defined by four pieces of information: the IP address and port number on one end, and the IP address and port number on the other end)
by not actively assigning a port, we implicitly ask the kernel to pick one for us when we get around to calling connect(2) on this socket
therefore, the next thing we need to do is to use DNS to find the IP address of the server, for which we use the getaddrinfo(3) function (which, as implied, is not a system call, though it will turn around and make system calls for you)
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
if((rc = getaddrinfo(dest_hostname, dest_port, &hints, &res)) != 0) {
printf("getaddrinfo failed: %s\n", gai_strerror(rc));
exit(1);
}
the first parameter to getaddrinfo is the name we want translated
the second parameter is the port number (as a string!)
the third parameter, hints, contains information about the kind of address we want to look up
in this case, we want something in the internet address family (AF_INET) and we want it to be applicable to TCP (SOCK_STREAM)
the fourth parameter, res, is where getaddrinfo will put the result: that is, the numerical IP address corresponding to the name we gave in the first parameter (plus some other stuff like the port number translated into an integer)
its return value indicates success or failure
the hints data structure actually has a bunch more fields (read about them in the getaddrinfo(3) manpage)
we need to make absolutely sure those fields are set to zero before we send the struct to getaddrinfo
which is the purpose of the memset call at the beginning of that block of code
(recall that it’s a stack variable, and stack memory is not initialized)
now that we’ve done the DNS, we’re ready to actually connect
if(connect(conn_fd, res->ai_addr, res->ai_addrlen) < 0) {
perror("connect");
exit(2);
}
the three parameters are straightforward:
- the file descriptor identifying the socket we created previously
- the result of the lookup we just performed
- and the length of that result record (helpfully, res has a field that already has this information)
when this system call returns, the connection has been established
(the address length needs to be specified because different protocols use different numbers of bits to specify addresses: eg, IP uses 32-bit address, IPv6 uses 128-bit addresses)
which means we can proceed to the boring part: a loop that reads data from the terminal, sends that data to the server, receives some data in response, and then prints the data it received
the loop ends when we enter end-of-file on the terminal of the client (which we can do by pressing Control-D)
while((n = read(0, buf, BUF_SIZE)) > 0) {
send(conn_fd, buf, n, 0);
n = recv(conn_fd, buf, BUF_SIZE, 0);
printf("received: ");
puts(buf);
}
again, pretty straightforward
note that we use the system calls send(2) and recv(2) to write to and read from the connection
they look very similar to write(2) and read(2), except they each have an extra argument
in fact, the first three arguments have the exact same meaning: a file descriptor, a buffer, and a length
I actually said last time that we can use write(2) and read(2) for network communication, and I didn’t lie
that fourth argument in both send(2) and recv(2) allows you to specify flags specific to network communication
if you don’t need to specify any flags, as in the example code here, this parameter is set to zero
in the case where you don’t need anything special, you could also just directly replace the call to send(2) with a call to write(2) and also replce the call to recv(2) with a call to read(2) (in both cases, ditch the final parameter)
I leave a proof of this as an exercise to the reader
let us look at the client in action before proceeding to the internals of the server
I have two terminals open, one on my laptop and the other on basin
I start the server on basin, with it listening on port 8000:
basin$ ./echo-server 8000
then I run the client on my laptop, connecting to the server on basin:
laptop$ ./echo-client basin.cs.middlebury.edu 8000
note that the server prints out an informative message when the client has connected (the IP address is that of my laptop):
new connection from 140.233.172.162:38102
and now when I type into the client, two things happen: - the server prints out a "." indicating that it received data - the client prints out an echo of the data it sent
I can type more stuff in the client and more dots will show up on the server and more echoes will show up on the client
when I’m done, I hit Ctrl-D in the client, which will cause it to exit
meanwhile, the server will notice that the client has closed the connection and it will print a newline
nothing terribly exciting, but it does demonstrate the realization of the moving parts we have to play with
now on to the server: echo-server.c
(review the diagram above to refresh your memory as to what the server is supposed to do)
again a bunch of header file includes, some constants, and a bunch of local variables in main
because it’s listening, not connecting, the server only needs to be given the desired port number on the command line:
listen_port = argv[1];
and the socket-creation step is the same:
listen_fd = socket(PF_INET, SOCK_STREAM, 0);
now, unlike the client, we need to actually bind to a port
the steps to accomplish this look eerily similar to the DNS-lookup steps in the client
the reason is that we use getaddrinfo to create the data structure we’re eventually going to pass to bind(2) (which will, unsurprisingly, actually bind the socket to a port)
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
if((rc = getaddrinfo(NULL, listen_port, &hints, &res)) != 0) {
printf("getaddrinfo failed: %s\n", gai_strerror(rc));
exit(1);
}
bind(listen_fd, res->ai_addr, res->ai_addrlen);
two differences
first, in the call to getaddrinfo, we don’t specify a hostname: we use NULL for the first parameter
second and relatedly, we also set the ai_flags field to AI_PASSIVE
the combination of these two differences will cause the server process to listen on all network devices on the machine
for example, my laptop has both a wired Ethernet port and a wifi radio
binding in this manner will allow it to accept incoming connections over either interface
once the socket has been bound to a port, we can tell it to start listening for incoming connections on that socket
listen(listen_fd, BACKLOG);
note that this listens for connections not for data
data may be sent/received only after the connection has been established
the second parameter is the number of unaccepted connections the kernel will keep around before beginning to reject new clients
so, having called listen(2) with a backlog of 10, clients can start to connect and the kernel will gladly allow them to do so even if the server never calls accept(2)… up to 10
then the kernel will turn them away… until the server process calls accept(2) and clears out some space in its queue
now we’ve got an infinite loop!
each iteration of this loop will manage a single connection
the loop body begins by accepting the new connection
addrlen = sizeof(remote_sa); conn_fd = accept(listen_fd, (struct sockaddr *) &remote_sa, &addrlen);
the important thing to notice here is that accept(2) returns a NEW file descriptor that corresponds to the now-active connection
and the file descriptor that represents the listening socket is still active
thus we have one fd for the active connection (upon which we can now send and receive data)
and a separate fd for the listen-for-new-connections situation
the call to accept(2) provides it with a data structure for it to fill in, which will describe the other end of the connection (sometimes called the "remote" end, to differentiate it from the "local" end)
what if a client never connects? what will accept(2) do?
absolutely nothing: it won’t even return
this is because accept(2) is a blocking function: it doesn’t return until it has been able to do what it was asked to do
read(2) and write(2) are also blocking, incidentally, but we are probably in the habit of providing them with data or disk quickly enough that we don’t consider the possibility that they might have to wait
we will see some examples of non-blocking stuff later on, but they require more complex handling
now we print out the IP address and port number of the remote end of the connection
remote_ip = inet_ntoa(remote_sa.sin_addr);
remote_port = ntohs(remote_sa.sin_port);
printf("new connection from %s:%d\n", remote_ip, remote_port);
the inet_ntoa function takes a numerical IP address as its argument and returns a pointer to a string representation
but the port number is just a number—except in big-endian format!
so we call ntohs on it to convert to the current computer’s format (which happens to be little-endian, because it’s x86)
ntohs stands for "network to host short"
meaning it’s converting a value of type "short" (which is the old-school name for a 16-bit integer) from network byte-order (big-endian) to host byte-order (in this case, little-endian)
even if machine was a big-endian machine, and thus used the same byte ordering, you would still want to use functions like ntohs
(in which case, ntohs would just be a no-op)
the reason is that it makes your code portable: you could just copy the source code and immediately compile it on a little-endian machine and it will just work because the implementation of ntohs on the little-endian machine will not be a no-op, but will do the Right Thing
next we have another while loop
while((bytes_received = recv(conn_fd, buf, BUF_SIZE, 0)) > 0) {
printf(".");
fflush(stdout);
/* send it back */
send(conn_fd, buf, bytes_received, 0);
}
it looks similar to the while loop in the client, except that the loop invariant involves reading from the connection rather than reading from the terminal
the style is the same, however, and we can infer (correctly) that recv will return 0 when the connection has been closed or less than zero if there has been an error
nothing terribly exciting
but again, we can change the send(2) and recv(2) to write(2) and read(2), respectively, if we want to
since the inner while loop will terminate when the connection has been closed by the remote end, we finish the outer loop’s interation by printing a newline and closing the fd we’ve been working with (close it just to be careful; the loop could have exited due to error)
let’s step back a bit and examine the behavior of the server
it accepts a new connection and then enters into a loop to handle that connection
and only when the connection has been fully handled and finished do we return to the top of the outer loop and accept a new connection
consider the following sequence of events:
- server process starts
- client A connects
- client B connects
the server won’t even accept(2) the connection from client B until client A has closed its connection
we can verify this
run the server in one terminal (which is a shell logged into basin)
basin$ ./echo-server 1234
run one client in a second terminal (on my laptop)
$ ./echo-client basin.cs.middlebury.edu 1234
run another client in a third terminal (also on my laptop)
$ ./echo-client basin.cs.middlebury.edu 1234
type in the first client window; behavior as expected
type in the second terminal; no data received!
press Ctrl-D in the first client, that client exits and the second client immediately sees all its pent-up output appear
because the server has finally gotten around to dealing with it
another question raised by the example above is: how do we service multiple clients simultaneously?
it seems crazy-limiting to not even accept a second incoming connection while we’re in the process of servicing another, and it is
a few options:
- we could fork off a new process to deal with each incoming connection
- we could spin off a thread to deal with each incoming connection
- or… something else
in the end-of-semester project, you will explore and implement the "something else"