Skip to content

Instantly share code, notes, and snippets.

@dmitru
Created May 16, 2013 19:37
Show Gist options
  • Save dmitru/5594435 to your computer and use it in GitHub Desktop.
Save dmitru/5594435 to your computer and use it in GitHub Desktop.
A simple UNIX socket server
// You can test your server programs with 'telnet' UNIX tool.
// see man telnet!
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/un.h>
int main(int argc, char *argv[])
{
if (argc < 2)
exit(1);
// 1. Create a socket
int listeningSocket = socket(AF_INET, SOCK_STREAM, 0);
if (socket == -1) {
perror("socket() error");
exit(errno);
}
puts("Socket created");
/* Enable address reuse */
// If you don't do this, the system will prohibit reuse of the port for
// some time, by default smth. about 3 minutes
int on = 1;
if (setsockopt(listeningSocket, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on))) {
perror("setsockopt() error");
exit(errno);
}
// 2. Bind the socket to an address
struct sockaddr_in serverAddr;
memset(&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = INADDR_ANY;
serverAddr.sin_port = htons(atoi(argv[1]));
// pitfall! Don't forget to cast the pointer into the correct type
if (bind(listeningSocket, (struct sockaddr *) &serverAddr, sizeof(serverAddr))) {
perror("bind() error");
exit(errno);
}
puts("Adress binded");
// 3. Make it listening
if (listen(listeningSocket, 3)) {
perror("listen() error");
exit(errno);
}
// 4. Process clients
for (;;) {
puts("Waiting for a client...");
int clientSocket;
struct sockaddr_in clientAddress;
socklen_t clientLen = sizeof(clientAddress);
clientSocket = accept(listeningSocket, (struct sockaddr *) &clientAddress, &clientLen);
if (clientSocket < 0) {
perror("accept() error");
exit(errno);
}
// While the client has smth to send, receive it and print on the screen
char c;
int recvStatus;
while ((recvStatus = recv(clientSocket, &c, 1, 0)) > 0)
{
printf("%c\n", c);
}
if (recvStatus < 0) {
perror("An error has occured");
exit(errno);
}
puts("A client has been connected");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment