-
C Server
I want to try to make a C server that allows multiple clients to connect and talk back and forth with the server, but I have no clue where to get started. I know the basics of what I have to do (set up sockets, wait for a connection, and use the socket to read/write), but the specifics is beyond me. How do I do this?
-
Plenty of stuff here and on Google detailing howto go about it.
-
I found this starter code but I'm not sure how to change it so that a) it accepts more than 1 client and b) gets rid of all the errors I get when I try to compile it.
Code:
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/file.h>
#include <signal.h>
#include <errno.h>
#include <time.h>
int main(){
int soc, ns, k;
int on = 1, status;
char buf[256];
struct sockaddr_in peer; /* Used to talk to a client */
struct sockaddr_in self; /* Used to contain info about self (for bind.) */
int peer_len = sizeof(peer);
char *host;
/* fill in own sockaddr_in structure */
self.sin_family = AF_INET;
self.sin_port = htons(PORT);
self.sin_addr.s_addr = INADDR_ANY;
bzero(&(self.sin_zero), 8);
peer.sin_family = AF_INET; /* fill in (as much as necessary) potential client info */
soc = socket(AF_INET, SOCK_STREAM, 0); /* get a listening socket "soc" */
/* tell the OS to connect the socket id "soc" and the sockaddr_in struct "self" */
bind(soc, (struct sockaddr *)&self, sizeof(self))
listen(soc, 1); /* tell the OS we are ready (accepting one call only) */
ns = accept(soc, (struct sockaddr *)&peer, &peer_len); /* wait for a connection */
k = read(ns, buf, sizeof(buf)); /* read from client on connected socket ns */
write(ns, buf, k); /* write back the same string to client: */
close(ns); /* clean up and exit */
close(soc);
return(0);
}
-
I don't think you'll be very successful by just trying to change other people's source.
Beej's Guide To Networking is a very good resource to learn network programming.
Beej's Guide to Network Programming
(It says buy as a book at the top, but there is a downloadable version further down the page)
It covers pretty much everything you need to know about networking and is easy to understand. Not really that long either.