Last active
April 12, 2016 00:57
-
-
Save evanharmon/853dbde3a24c64ae8d95 to your computer and use it in GitHub Desktop.
Simple base server in C
This file contains hidden or 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 <stdlib.h> | |
| #include <strings.h> | |
| #include <unistd.h> | |
| #include <sys/types.h> | |
| #include <sys/socket.h> | |
| #include <netinet/in.h> | |
| /* adapted from http://www.cs.rpi.edu/~moorthy/Courses/os98/Pgms/socket.html */ | |
| void error(char *msg) { | |
| perror(msg); | |
| exit(1); | |
| } | |
| int main(int argc, char *argv[]) { | |
| int sockfd, newsockfd, portno, clilen; | |
| char buffer[256]; | |
| struct sockaddr_in serv_addr, cli_addr; | |
| int n; | |
| if (argc < 2) { | |
| fprintf(stderr, "Error: no port provided\n"); | |
| exit(1); | |
| } | |
| /* first call to socket() */ | |
| sockfd = socket(AF_INET, SOCK_STREAM, 0); | |
| if (sockfd < 0) | |
| error("Error opening socket"); | |
| /* Initialize socket structure */ | |
| bzero((char *) &serv_addr, sizeof(serv_addr)); | |
| portno = atoi(argv[1]); | |
| serv_addr.sin_family = AF_INET; | |
| serv_addr.sin_addr.s_addr = INADDR_ANY; | |
| serv_addr.sin_port = htons(portno); | |
| /* Bind host address using bind() call */ | |
| if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) | |
| error("Error on binding"); | |
| /* Start listening */ | |
| listen(sockfd, 5); | |
| socklen_t clilen = sizeof(cli_addr); | |
| /* Accept connection from client */ | |
| newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen); | |
| if (newsockfd < 0) | |
| error("Error on accept"); | |
| /* if connection established, start communicating */ | |
| bzero(buffer, 256); | |
| n = read(newsockfd, buffer, 255); | |
| if (n < 0) error("Error reading from socket"); | |
| printf("Here is the message: %s\n", buffer); | |
| /* write a response to client */ | |
| n = write(newsockfd, "I got your message", 18); | |
| if (n < 0) error("Error writing to socket"); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment