Who should and who does are often different. There are laws and contracts to consider as well as "common law." In my own view, forcing a faculty member to give up all rights to the intellectual property (IP) that he/she develops is just wrong. However the law is the law. Contracts intervene. A program developed in a class for a client is normally done under contract and the client likely owns everything. But you know this going in.
However, a faculty member can't, morally at least, appropriate a student's work unless contracts are in place. Faculty member should, of course, give proper attribution for anything used and also seek permission if there is something useful to be reused. I don't think it is wise for a professor to assume otherwise.
One possibly useful suggestion is to ask the students at the beginning of a term to agree that code they write is done so under GPL or similar license. But it needs to be agreed to.
In general, though, "if you create it, you own it". That is probably not universal, but widely held.
In situations in which contract or the law do give faculty rights to IP created by students everyone is better served, I think, if the faculty member still respects the more general rights of the student. Just because you can appropriate someone else's work doesn't imply that you should.
On the other hand, if the professor provides the question and guidance in the solution, he/she may have some IP rights to the product.
For what it is worth, companies also appropriate the work of employees, but under contract. That is mostly well justified and needed, but there are some variations on it that are also immoral in my view. Preventing a researcher from ever working on the same problems after employment ends should not be allowed in a contract and such should be struck down. But, then, I'm not a lawyer or judge.
Beyond the narrow question it is possible to think "outside the box." If a faculty member normally publishes work on a website he/she can, with the student's permission, publish a student's work under the student's name. This gives the student some visibility and adds a bit of the professor's reputation to that of the student, providing a boost.
I've also heard of situations in which a student and prof go into business together based on joint work.