Server.c

From Organic Design wiki
Revision as of 21:56, 1 July 2006 by Rob (talk | contribs)

// - todo: don't exit on connect errors, keep trying every 10s // Includes for socket (trying to use one source cpp for osx,win32,*ux)

  1. ifdef WINDOWS
  2. include <winsock.h>
  3. else
  4. include <sys/socket.h>
  5. include <netinet/in.h>
  6. include <arpa/inet.h>
  7. include <netdb.h>
  8. include <unistd.h>
  9. endif

// Socket

  1. define LISTENPORT 2012
  2. define BACKLOG 10
  3. define MSG "stink ow!"

int sock, conn; struct sockaddr_in my_addr, client_addr; int sockopt_on = 1; int sa_in_size = sizeof(struct sockaddr_in); char response[80];

//get a socket if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) { perror("socket"); exit(1); }

//make it reusable if (setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&sockopt_on,sizeof(int)) == -1) { perror("setsockopt"); exit(1); }

//first zero the struct memset((char *) &my_addr, 0, sa_in_size);

//now fill in the fields we need my_addr.sin_family = PF_INET; my_addr.sin_port = htons(LISTENPORT); my_addr.sin_addr.s_addr = htonl(INADDR_ANY);

//bind our socket to the port if (bind(sock,(struct sockaddr *)&my_addr, sa_in_size) == -1) { perror("bind"); exit(1); }

//start listening for incoming connections if (listen(sock,BACKLOG) == -1) { perror("listen"); exit(1); }

while(1) { //grab connections conn = accept(sock, (struct sockaddr *)&client_addr, &sa_in_size); if (conn == -1) { perror("accept"); exit(1); }

//log the connecter printf("got connection from %s\n", inet_ntoa(client_addr.sin_addr));

//send a greeting if (send(conn,MSG,strlen(MSG)+1,0) == -1) { perror("send"); }

//get the reply if (recv(conn, &response, 80, 0) == -1) { perror("recv"); } printf("The client says \"%s\"\n",&response); close(conn);

}