/*------------------------------------------------------------------------------------------------------------
ÆÄÀϸí : myecho_server.c
±â ´É : echo ¼ºñ½º¸¦ ¼öÇàÇÏ´Â ¼¹ö
ÄÄÆÄÀÏ : cc -o myecho_server myecho_server.c -lsocket -lnsl
½ÇÇ࿹ : myecho_server 2049
--------------------------------------------------------------------------------------------------------------*/
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define BUF_LEN 128
int main(int argc, char *argv[]) {
struct sockaddr_in server_addr, client_addr;
int server_fd, client_fd; /* ¼ÒÄϹøÈ£ */
int len, len_out;
int port; /* Æ÷Æ®¹øÈ£ */
char buf[BUF_LEN+1];
if(argc != 2) {
printf("usage: %s port\n", argv[0]);
return -1;
}
port = atoi(argv[1]); /* Æ÷Æ®¹øÈ£´Â ¸í·É ÀÎÀÚ·Î ÀÔ·Â */
/* ¼ÒÄÏ »ý¼º */
if((server_fd = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
printf("Server: Can't open stream socket.");
return 0;
}
/* server_addrÀ» '\0'À¸·Î ÃʱâÈ */
bzero((char *)&server_addr, sizeof(server_addr));
/* server_addr ¼¼Æà */
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(port);
/* bind() È£Ãâ */
if(bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
printf("Server: Can't bind local address.\n");
return 0;
}
/* ¼ÒÄÏÀ» ¼öµ¿ ´ë±â¸ðµå·Î ¼¼Æà */
listen(server_fd, 5);
/* iterative echo ¼ºñ½º ¼öÇà */
while(1) {
printf("Server : waiting connection request.\n");
len = sizeof(client_addr);
/* ¿¬°á¿äûÀ» ±â´Ù¸² */
client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &len);
if(client_fd < 0) {
printf("Server: accept failed.\n");
return 0;
}
printf("Server : client connected.\n");
len_out = read(client_fd, buf, sizeof(buf));
write(client_fd, buf, len_out);
close(client_fd);
}
close(server_fd);
}
|