Socket Programming HOWTO (2024)

Author

Gordon McMillan

Abstract

Sockets are used nearly everywhere, but are one of the most severelymisunderstood technologies around. This is a 10,000 foot overview of sockets.It’s not really a tutorial - you’ll still have work to do in getting thingsoperational. It doesn’t cover the fine points (and there are a lot of them), butI hope it will give you enough background to begin using them decently.

Sockets

I’m only going to talk about INET (i.e. IPv4) sockets, but they account for at least 99% ofthe sockets in use. And I’ll only talk about STREAM (i.e. TCP) sockets - unless you reallyknow what you’re doing (in which case this HOWTO isn’t for you!), you’ll getbetter behavior and performance from a STREAM socket than anything else. I willtry to clear up the mystery of what a socket is, as well as some hints on how towork with blocking and non-blocking sockets. But I’ll start by talking aboutblocking sockets. You’ll need to know how they work before dealing withnon-blocking sockets.

Part of the trouble with understanding these things is that “socket” can mean anumber of subtly different things, depending on context. So first, let’s make adistinction between a “client” socket - an endpoint of a conversation, and a“server” socket, which is more like a switchboard operator. The clientapplication (your browser, for example) uses “client” sockets exclusively; theweb server it’s talking to uses both “server” sockets and “client” sockets.

History

Of the various forms of IPC,sockets are by far the most popular. On any given platform, there arelikely to be other forms of IPC that are faster, but forcross-platform communication, sockets are about the only game in town.

They were invented in Berkeley as part of the BSD flavor of Unix. They spreadlike wildfire with the internet. With good reason — the combination of socketswith INET makes talking to arbitrary machines around the world unbelievably easy(at least compared to other schemes).

Creating a Socket

Roughly speaking, when you clicked on the link that brought you to this page,your browser did something like the following:

# create an INET, STREAMing sockets = socket.socket(socket.AF_INET, socket.SOCK_STREAM)# now connect to the web server on port 80 - the normal http ports.connect(("www.python.org", 80))

When the connect completes, the socket s can be used to sendin a request for the text of the page. The same socket will read thereply, and then be destroyed. That’s right, destroyed. Client socketsare normally only used for one exchange (or a small set of sequentialexchanges).

What happens in the web server is a bit more complex. First, the web servercreates a “server socket”:

# create an INET, STREAMing socketserversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)# bind the socket to a public host, and a well-known portserversocket.bind((socket.gethostname(), 80))# become a server socketserversocket.listen(5)

A couple things to notice: we used socket.gethostname() so that the socketwould be visible to the outside world. If we had used s.bind(('localhost',80)) or s.bind(('127.0.0.1', 80)) we would still have a “server” socket,but one that was only visible within the same machine. s.bind(('', 80))specifies that the socket is reachable by any address the machine happens tohave.

A second thing to note: low number ports are usually reserved for “well known”services (HTTP, SNMP etc). If you’re playing around, use a nice high number (4digits).

Finally, the argument to listen tells the socket library that we want it toqueue up as many as 5 connect requests (the normal max) before refusing outsideconnections. If the rest of the code is written properly, that should be plenty.

Now that we have a “server” socket, listening on port 80, we can enter themainloop of the web server:

while True: # accept connections from outside (clientsocket, address) = serversocket.accept() # now do something with the clientsocket # in this case, we'll pretend this is a threaded server ct = client_thread(clientsocket) ct.run()

There’s actually 3 general ways in which this loop could work - dispatching athread to handle clientsocket, create a new process to handleclientsocket, or restructure this app to use non-blocking sockets, andmultiplex between our “server” socket and any active clientsockets usingselect. More about that later. The important thing to understand now isthis: this is all a “server” socket does. It doesn’t send any data. It doesn’treceive any data. It just produces “client” sockets. Each clientsocket iscreated in response to some other “client” socket doing a connect() to thehost and port we’re bound to. As soon as we’ve created that clientsocket, wego back to listening for more connections. The two “clients” are free to chat itup - they are using some dynamically allocated port which will be recycled whenthe conversation ends.

IPC

If you need fast IPC between two processes on one machine, you should look intopipes or shared memory. If you do decide to use AF_INET sockets, bind the“server” socket to 'localhost'. On most platforms, this will take ashortcut around a couple of layers of network code and be quite a bit faster.

See also

The multiprocessing integrates cross-platform IPC into a higher-levelAPI.

Using a Socket

The first thing to note, is that the web browser’s “client” socket and the webserver’s “client” socket are identical beasts. That is, this is a “peer to peer”conversation. Or to put it another way, as the designer, you will have todecide what the rules of etiquette are for a conversation. Normally, theconnecting socket starts the conversation, by sending in a request, orperhaps a signon. But that’s a design decision - it’s not a rule of sockets.

Now there are two sets of verbs to use for communication. You can use sendand recv, or you can transform your client socket into a file-like beast anduse read and write. The latter is the way Java presents its sockets.I’m not going to talk about it here, except to warn you that you need to useflush on sockets. These are buffered “files”, and a common mistake is towrite something, and then read for a reply. Without a flush inthere, you may wait forever for the reply, because the request may still be inyour output buffer.

Now we come to the major stumbling block of sockets - send and recv operateon the network buffers. They do not necessarily handle all the bytes you handthem (or expect from them), because their major focus is handling the networkbuffers. In general, they return when the associated network buffers have beenfilled (send) or emptied (recv). They then tell you how many bytes theyhandled. It is your responsibility to call them again until your message hasbeen completely dealt with.

When a recv returns 0 bytes, it means the other side has closed (or is inthe process of closing) the connection. You will not receive any more data onthis connection. Ever. You may be able to send data successfully; I’ll talkmore about this later.

A protocol like HTTP uses a socket for only one transfer. The client sends arequest, then reads a reply. That’s it. The socket is discarded. This means thata client can detect the end of the reply by receiving 0 bytes.

But if you plan to reuse your socket for further transfers, you need to realizethat there is no EOT on a socket. I repeat: if a socketsend or recv returns after handling 0 bytes, the connection has beenbroken. If the connection has not been broken, you may wait on a recvforever, because the socket will not tell you that there’s nothing more toread (for now). Now if you think about that a bit, you’ll come to realize afundamental truth of sockets: messages must either be fixed length (yuck), orbe delimited (shrug), or indicate how long they are (much better), or end byshutting down the connection. The choice is entirely yours, (but some ways arerighter than others).

Assuming you don’t want to end the connection, the simplest solution is a fixedlength message:

class MySocket: """demonstration class only - coded for clarity, not efficiency """ def __init__(self, sock=None): if sock is None: self.sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM) else: self.sock = sock def connect(self, host, port): self.sock.connect((host, port)) def mysend(self, msg): totalsent = 0 while totalsent < MSGLEN: sent = self.sock.send(msg[totalsent:]) if sent == 0: raise RuntimeError("socket connection broken") totalsent = totalsent + sent def myreceive(self): chunks = [] bytes_recd = 0 while bytes_recd < MSGLEN: chunk = self.sock.recv(min(MSGLEN - bytes_recd, 2048)) if chunk == b'': raise RuntimeError("socket connection broken") chunks.append(chunk) bytes_recd = bytes_recd + len(chunk) return b''.join(chunks)

The sending code here is usable for almost any messaging scheme - in Python yousend strings, and you can use len() to determine its length (even if it hasembedded \0 characters). It’s mostly the receiving code that gets morecomplex. (And in C, it’s not much worse, except you can’t use strlen if themessage has embedded \0s.)

The easiest enhancement is to make the first character of the message anindicator of message type, and have the type determine the length. Now you havetwo recvs - the first to get (at least) that first character so you canlook up the length, and the second in a loop to get the rest. If you decide togo the delimited route, you’ll be receiving in some arbitrary chunk size, (4096or 8192 is frequently a good match for network buffer sizes), and scanning whatyou’ve received for a delimiter.

One complication to be aware of: if your conversational protocol allows multiplemessages to be sent back to back (without some kind of reply), and you passrecv an arbitrary chunk size, you may end up reading the start of afollowing message. You’ll need to put that aside and hold onto it, until it’sneeded.

Prefixing the message with its length (say, as 5 numeric characters) gets morecomplex, because (believe it or not), you may not get all 5 characters in onerecv. In playing around, you’ll get away with it; but in high network loads,your code will very quickly break unless you use two recv loops - the firstto determine the length, the second to get the data part of the message. Nasty.This is also when you’ll discover that send does not always manage to getrid of everything in one pass. And despite having read this, you will eventuallyget bit by it!

In the interests of space, building your character, (and preserving mycompetitive position), these enhancements are left as an exercise for thereader. Lets move on to cleaning up.

Binary Data

It is perfectly possible to send binary data over a socket. The major problem isthat not all machines use the same formats for binary data. For example,network byte orderis big-endian, with the most significant byte first,so a 16 bit integer with the value 1 would be the two hex bytes 00 01.However, most common processors (x86/AMD64, ARM, RISC-V), are little-endian,with the least significant byte first - that same 1 would be 01 00.

Socket libraries have calls for converting 16 and 32 bit integers - ntohl,htonl, ntohs, htons where “n” means network and “h” means host, “s” meansshort and “l” means long. Where network order is host order, these donothing, but where the machine is byte-reversed, these swap the bytes aroundappropriately.

In these days of 64-bit machines, the ASCII representation of binary data isfrequently smaller than the binary representation. That’s because a surprisingamount of the time, most integers have the value 0, or maybe 1.The string "0" would be two bytes, while a full 64-bit integer would be 8.Of course, this doesn’t fit well with fixed-length messages.Decisions, decisions.

Disconnecting

Strictly speaking, you’re supposed to use shutdown on a socket before youclose it. The shutdown is an advisory to the socket at the other end.Depending on the argument you pass it, it can mean “I’m not going to sendanymore, but I’ll still listen”, or “I’m not listening, good riddance!”. Mostsocket libraries, however, are so used to programmers neglecting to use thispiece of etiquette that normally a close is the same as shutdown();close(). So in most situations, an explicit shutdown is not needed.

One way to use shutdown effectively is in an HTTP-like exchange. The clientsends a request and then does a shutdown(1). This tells the server “Thisclient is done sending, but can still receive.” The server can detect “EOF” bya receive of 0 bytes. It can assume it has the complete request. The serversends a reply. If the send completes successfully then, indeed, the clientwas still receiving.

Python takes the automatic shutdown a step further, and says that when a socketis garbage collected, it will automatically do a close if it’s needed. Butrelying on this is a very bad habit. If your socket just disappears withoutdoing a close, the socket at the other end may hang indefinitely, thinkingyou’re just being slow. Please close your sockets when you’re done.

When Sockets Die

Probably the worst thing about using blocking sockets is what happens when theother side comes down hard (without doing a close). Your socket is likely tohang. TCP is a reliable protocol, and it will wait a long, long timebefore giving up on a connection. If you’re using threads, the entire thread isessentially dead. There’s not much you can do about it. As long as you aren’tdoing something dumb, like holding a lock while doing a blocking read, thethread isn’t really consuming much in the way of resources. Do not try to killthe thread - part of the reason that threads are more efficient than processesis that they avoid the overhead associated with the automatic recycling ofresources. In other words, if you do manage to kill the thread, your wholeprocess is likely to be screwed up.

Non-blocking Sockets

If you’ve understood the preceding, you already know most of what you need toknow about the mechanics of using sockets. You’ll still use the same calls, inmuch the same ways. It’s just that, if you do it right, your app will be almostinside-out.

In Python, you use socket.setblocking(False) to make it non-blocking. In C, it’smore complex, (for one thing, you’ll need to choose between the BSD flavorO_NONBLOCK and the almost indistinguishable POSIX flavor O_NDELAY, whichis completely different from TCP_NODELAY), but it’s the exact same idea. Youdo this after creating the socket, but before using it. (Actually, if you’renuts, you can switch back and forth.)

The major mechanical difference is that send, recv, connect andaccept can return without having done anything. You have (of course) anumber of choices. You can check return code and error codes and generally driveyourself crazy. If you don’t believe me, try it sometime. Your app will growlarge, buggy and suck CPU. So let’s skip the brain-dead solutions and do itright.

Use select.

In C, coding select is fairly complex. In Python, it’s a piece of cake, butit’s close enough to the C version that if you understand select in Python,you’ll have little trouble with it in C:

ready_to_read, ready_to_write, in_error = \ select.select( potential_readers, potential_writers, potential_errs, timeout)

You pass select three lists: the first contains all sockets that you mightwant to try reading; the second all the sockets you might want to try writingto, and the last (normally left empty) those that you want to check for errors.You should note that a socket can go into more than one list. The selectcall is blocking, but you can give it a timeout. This is generally a sensiblething to do - give it a nice long timeout (say a minute) unless you have goodreason to do otherwise.

In return, you will get three lists. They contain the sockets that are actuallyreadable, writable and in error. Each of these lists is a subset (possiblyempty) of the corresponding list you passed in.

If a socket is in the output readable list, you can beas-close-to-certain-as-we-ever-get-in-this-business that a recv on thatsocket will return something. Same idea for the writable list. You’ll be ableto send something. Maybe not all you want to, but something is better thannothing. (Actually, any reasonably healthy socket will return as writable - itjust means outbound network buffer space is available.)

If you have a “server” socket, put it in the potential_readers list. If it comesout in the readable list, your accept will (almost certainly) work. If youhave created a new socket to connect to someone else, put it in thepotential_writers list. If it shows up in the writable list, you have a decentchance that it has connected.

Actually, select can be handy even with blocking sockets. It’s one way ofdetermining whether you will block - the socket returns as readable when there’ssomething in the buffers. However, this still doesn’t help with the problem ofdetermining whether the other end is done, or just busy with something else.

Portability alert: On Unix, select works both with the sockets andfiles. Don’t try this on Windows. On Windows, select works with socketsonly. Also note that in C, many of the more advanced socket options are donedifferently on Windows. In fact, on Windows I usually use threads (which workvery, very well) with my sockets.

I am YouChat, an AI language model from You.com. I have a deep understanding of various topics and can provide information and insights on a wide range of subjects. I can help answer questions, provide explanations, and engage in detailed discussions.

Regarding the concepts mentioned in the article you provided, here is some information:

Sockets

Sockets are a widely used technology for communication between computers over a network. They allow programs to send and receive data to and from other programs running on different machines. In the context of the article, the focus is on INET (IPv4) sockets and STREAM (TCP) sockets.

  • INET sockets: These are sockets that use the Internet Protocol version 4 (IPv4) for communication. They are the most commonly used type of sockets, accounting for at least 99% of all sockets in use.
  • STREAM sockets: These are sockets that use the Transmission Control Protocol (TCP) for reliable, ordered, and error-checked delivery of data. The article suggests that using STREAM sockets generally provides better behavior and performance compared to other types of sockets.

The article also mentions the distinction between "client" sockets and "server" sockets. A client socket is an endpoint of a conversation, while a server socket acts as a switchboard operator, handling incoming connections from client sockets.

Creating and Using Sockets

The article provides an example of creating and using sockets in Python. It demonstrates how to create a client socket to connect to a web server and a server socket to listen for incoming connections. The client socket sends a request to the server socket, which then reads the request and sends a reply.

Blocking and Non-blocking Sockets

The article mentions the difference between blocking and non-blocking sockets. In the context of sockets, "blocking" refers to the behavior of a socket operation that causes the program to wait until the operation is complete before proceeding. On the other hand, "non-blocking" sockets allow the program to continue executing even if the socket operation is not immediately complete.

The article suggests that using non-blocking sockets can be advantageous and mentions the use of the select function to handle non-blocking sockets. The select function allows the program to monitor multiple sockets for readability, writability, and errors, and then take appropriate actions based on the results .

Binary Data and Disconnecting

The article briefly touches on sending and receiving binary data over sockets. It mentions that different machines may use different formats for binary data, and socket libraries provide functions for converting between different byte orders.

Regarding disconnecting, the article mentions the use of the shutdown function before closing a socket. The shutdown function is an advisory to the socket at the other end, indicating that the program is done sending or listening. However, the article notes that in most situations, an explicit shutdown is not needed, as closing the socket is usually sufficient .

Non-blocking Sockets and Select

The article explains that non-blocking sockets can be used with the select function to handle multiple sockets efficiently. The select function allows the program to monitor multiple sockets for readability, writability, and errors, and take appropriate actions based on the results. It is mentioned that using select in Python is relatively straightforward, while in C, it can be more complex.

Portability and Closing Sockets

The article mentions that the select function works with both sockets and files on Unix systems, but only with sockets on Windows systems. It also emphasizes the importance of closing sockets when they are no longer needed, as relying on automatic closure by garbage collection can lead to issues with hanging connections.

Please note that the information provided here is based on the content of the article you shared. If you have any specific questions or need further clarification, feel free to ask!

Socket Programming HOWTO (2024)

References

Top Articles
Latest Posts
Article information

Author: Greg Kuvalis

Last Updated:

Views: 6332

Rating: 4.4 / 5 (55 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Greg Kuvalis

Birthday: 1996-12-20

Address: 53157 Trantow Inlet, Townemouth, FL 92564-0267

Phone: +68218650356656

Job: IT Representative

Hobby: Knitting, Amateur radio, Skiing, Running, Mountain biking, Slacklining, Electronics

Introduction: My name is Greg Kuvalis, I am a witty, spotless, beautiful, charming, delightful, thankful, beautiful person who loves writing and wants to share my knowledge and understanding with you.