Last active
February 9, 2017 00:17
-
-
Save p4bl0-/bc4b81cdda3e55ed6c9568399db54e2d to your computer and use it in GitHub Desktop.
Premier programme TCP : echo server simple.
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 <strings.h> | |
#include <unistd.h> | |
#include <sys/types.h> | |
#include <sys/socket.h> | |
#include <netinet/in.h> | |
#include <errno.h> | |
int | |
main (int argc, char *argv[]) | |
{ | |
int server; | |
int port; | |
struct sockaddr_in srv_addr; | |
int opt; | |
int client; | |
uint8_t buf[1024]; | |
int len; | |
if (argc != 2) { | |
fprintf(stderr, "Usage: %s <port>\n", argv[0]); | |
exit(1); | |
} | |
port = atoi(argv[1]); | |
server = socket(AF_INET, SOCK_STREAM, 0); | |
if (server < 0) { | |
perror("socket"); | |
exit(1); | |
} | |
opt = 1; | |
if (setsockopt(server, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0) { | |
perror("setsockopt"); | |
exit(1); | |
} | |
srv_addr.sin_family = AF_INET; | |
srv_addr.sin_addr.s_addr = htonl(INADDR_ANY); | |
srv_addr.sin_port = htons(port); | |
if (bind(server, (struct sockaddr *) &srv_addr, sizeof(srv_addr)) < 0) { | |
perror("bind"); | |
exit(1); | |
} | |
if (listen(server, 2) < 0) { | |
perror("bind"); | |
exit(1); | |
} | |
if ((client = accept(server, NULL, 0)) < 0) { | |
perror("accept"); | |
exit(1); | |
} | |
for (;;) { | |
bzero(buf, sizeof(buf)); | |
if ((len = read(client, buf, sizeof(buf))) < 0) { | |
perror("read"); | |
} | |
if (len == 0) { | |
break; | |
} | |
if (write(client, buf, len) < 0) { | |
perror("write"); | |
} | |
} | |
close(client); | |
close(server); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment