Created
April 14, 2011 11:17
-
-
Save flaneur2020/919282 to your computer and use it in GitHub Desktop.
simple echo server
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 <stdlib.h> | |
#include <unistd.h> | |
#include <errno.h> | |
#include <string.h> | |
#include <sys/socket.h> | |
#include <sys/types.h> | |
#include <netinet/in.h> | |
// | |
#define LISTEN_SIZ 10 | |
#define BUF_SIZ 1024 | |
#define PORT 8888 | |
int main(int argc, char **argv){ | |
int sockfd, connfd; | |
int r, tmp; | |
int port; | |
size_t salen; | |
struct sockaddr_in servaddr; | |
struct sockaddr_in cliaddr; | |
char buf[BUF_SIZ]; | |
sockfd = socket(AF_INET, SOCK_STREAM, 0); | |
if (sockfd < 0) { | |
printf("bad socket().\n"); | |
exit(sockfd); | |
} | |
tmp = 1; | |
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof(tmp)); | |
port = PORT; | |
servaddr.sin_family = AF_INET; | |
servaddr.sin_addr.s_addr = htonl(INADDR_ANY); | |
servaddr.sin_port = htons(port); | |
r = bind(sockfd, (struct sockaddr*) &servaddr, sizeof(servaddr)); | |
if (r < 0) { | |
printf("bad bind(). %s\n", strerror(errno)); | |
exit(r); | |
} | |
r = listen(sockfd, LISTEN_SIZ); | |
if (r < 0) { | |
printf("bad listen().\n"); | |
exit(r); | |
} | |
salen = sizeof(struct sockaddr_in); | |
for(;;) { | |
printf("waiting connection...\n"); | |
connfd = accept(sockfd, (struct sockaddr*)&cliaddr, &salen); | |
if (connfd < 0) { | |
printf("bad accept()."); | |
exit(connfd); | |
} | |
memset(buf, 0, BUF_SIZ); | |
while((r = read(connfd, buf, BUF_SIZ))>0) { | |
if (r < 0) { | |
printf("bad readn()"); | |
} | |
buf[r] = '\0'; | |
printf("> %d: %s", r, buf); | |
write(connfd, buf, r); | |
printf("> send: %s", buf); | |
memset(buf, 0, BUF_SIZ); | |
} | |
close(connfd); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment