본문 바로가기

IT

timeserv.c

// 서버를 구동하는 방법은 아래의 시퀀스를 따라 가는 겁니다.


// 1. 소켓을 만듭니다.


// 2. 바인딩을 합니다. (호스트, 포트)


// 3. 리슨


// 4. 어셉ㅌ


// 어때요, 쉽죠?


#include <stdio.h>

#include <unistd.h>

#include <sys/types.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <netdb.h>

#include <time.h>

#include <strings.h>


#define PORTNUM 5084

#define HOSTLEN 256

#define oops(m) {perror(m); exit(1);}


int main(int ac, char *av[])

{

struct sockaddr_in saddr;  // 본래 bind 할땐 struct sockaddr * 타입인데,4버전 인터넷을 사용할때 sockaddr_in 을 쓰고

struct hostent *hp;            // bind 할 때 sockaddr 로 타입 캐스팅함.

char hostname[HOSTLEN];

int sock_id, sock_fd;

FILE *sock_fp;

char *ctime();

time_t thetime;


sock_id = socket(PF_INET, SOCK_STREAM, 0); // domain : HP나 APPLE TALK 같은 것도 있음 ,

if (sock_id == -1)                                             //  type : 스트림 : SSH, DGRAM : HTTP

oops("socket");                                       // protocol : default 는 0.


bzero((void*)&saddr, sizeof(saddr));


gethostname(hostname, HOSTLEN);

hp = gethostbyname(hostname);


bcopy((void*)hp->h_addr, (void*)&saddr.sin_addr, hp->h_length); // h_addr 은 0으로 define. 

saddr.sin_port = htons(PORTNUM);

saddr.sin_family = AF_INET;


if(bind(sock_id, (struct sockaddr *)&saddr, sizeof(saddr))!=0) // 이 위에서 saddr의 수정이 있으니 윗부분을 잘 보세요

oops("bind");


if(listen(sock_id, 1) != 0) // 큐 사이즈 1

oops("listen");


while(1)

{

sock_fd=accept(sock_id, NULL, NULL);

printf("wow i got a call\n");

if(sock_fd==-1)

oops("accept");


sock_fp = fdopen(sock_fd,"w");

if(sock_fp == NULL)

oops("fdopen");


thetime = time(NULL);


fprintf(sock_fp, "the time here is.. ");

fprintf(sock_fp, " %s", ctime(&thetime));

fclose(sock_fp);

}

}



'IT' 카테고리의 다른 글

rls.c  (0) 2014.11.23
timeclnt.c  (0) 2014.11.20
popen example  (0) 2014.11.19
tiny bc  (0) 2014.11.19
theFinale.c  (0) 2014.11.12