views:

1127

answers:

6

I'm just starting out doing some basic network programming with C, and I found all these things about sockets and they all seem very convoluted. Maybe opening sockets with C is just convoluted itself, but I would like to know the simplest and most effective way to open and write data to a socket in the C programming language.

Thanks

A: 

Reading and writing from basic sockets is not any harder than reading and writing normal files (just use recv instead of read and send instead if write). Things get a little trickey when you need to open a socket. The reason for that is because there are many different ways to communicate using sockets (TCP, UDP, etc).

SoapBox
what you say is true on real operating systems, but unfortunately Windows makes it somewhat harder than using a file simply by drawing a distinction between sockets and files.
rmeador
+6  A: 

You're right, using sockets in C has a difficult syntax. Later languages like Java and Python make it a snap by comparison. The best tutorial I've found for doing socket programming in C is Beej's Guide to Network Programming. I recommend you start at the beginning to get a good overview, but if you just need to get some code working now, you can skip ahead to the section titled Client-Server Background.

Good luck!

Bill the Lizard
A: 

You might want to try Tcp4u, it's free any makes socket programming very easy.

http://www.jounin.net/tcp4u.html

FigBug
+5  A: 

You don't mention what platform you are on, but a copy of Unix Network Programming by Stevens would be a good addition to your bookshelf. Most operating systems implement Berkley Sockets using socket, bind, connect, etc.

Brian C. Lane
I was trying to remember the name of that book for my own answer but it's currently in storage. This is the bible for socket programming.
paxdiablo
Yeah, that is a great book. I keep it within arm's reach at work.
Bill the Lizard
All Stevens' books are great but UNP is the best. Both volumes.
qrdl
A: 

Unless you write a network daemon, most networking in C can be done at a higher level than using directly the sockets, by using appropriate libraries.

For instance, if you just want to retrieve a file with HTTP, use Neon or libcurl. It will be simpler, it will be at a higher level and you will have gratis SSL, IPv6, etc.

bortzmeyer
Several down votes and not one comment to explain why. This tells a lot about the technical level of many SO users...
bortzmeyer
More likely it's a battle between people who agree with you and people who think you are not answering the question asked.
David Sykes
A: 

Much good advice here so far. I generally write in C++, but you can find some use in a white paper I wrote "How to Avoid the Top Ten Sockets Programming Errors" - ignore the advice to use the ACE toolkit (since it requires C++) but take note of the socket errors in the paper - they're easy to make and hard to find, especially for a beginner. http://www.riverace.com/sockets10.htm