Created
July 17, 2015 22:57
-
-
Save Tombert/60f2d0545e7256fb42bc to your computer and use it in GitHub Desktop.
basicserver.c
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <unistd.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <sys/socket.h> | |
#include <netinet/ip.h> /* superset of previous */ | |
int main( int argc, char **argv){ | |
int tcp_socket; | |
int newsocket; | |
int port = atoi(argv[1]); | |
struct sockaddr_in server, client; | |
if((tcp_socket = socket(AF_INET, SOCK_STREAM, 0)) < 0){ | |
printf("There was an error making the socket: %m\n"); | |
return 1; | |
} | |
server.sin_family = AF_INET; | |
server.sin_addr.s_addr = INADDR_ANY; | |
server.sin_port = htons(port); | |
if(bind(tcp_socket, (struct sockaddr *) &server, sizeof(server)) < 0){ | |
printf("ERROR: %m\n"); | |
return 1; | |
} | |
if(listen(tcp_socket, 10) < 0){ | |
printf("Error:%m\n"); | |
return 1; | |
} | |
socklen_t clilen = sizeof(client); | |
if((newsocket = accept(tcp_socket, (struct sockaddr *) &client, &clilen)) < 0){ | |
printf("Error:%m\n"); | |
return 1; | |
} | |
int length; | |
char buffer[256]; | |
while(1){ | |
if((length = read(newsocket, buffer,255)) < 0) { | |
printf("Error: %m \n"); | |
return 1; | |
} | |
if(write(newsocket,buffer, length) < 0){ | |
printf("Error: %m \n"); | |
return 1; | |
} | |
} | |
/* close(newsocket); */ | |
/* close(socket); */ | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment