반응형

[list.c]

[result]


[host 상에서 구현] 

[gate@localhost gate]$ cat ls_server.c

#include <stdio.h>

#include <netinet/in.h>

#include <sys/socket.h>

#include <dirent.h>


#define PORT 9080


char err_1[]="Directory error";

char rBuffer[BUFSIZ];


main()

{

int c_socket,s_socket;

struct sockaddr_in s_addr,c_addr;

int len, length;

int n,i;


char *temp;

DIR *dp;

struct dirent *dir;

s_socket=socket(PF_INET,SOCK_STREAM,0);

memset(&s_addr,0,sizeof(s_addr));

s_addr.sin_addr.s_addr=htonl(INADDR_ANY);

s_addr.sin_family=AF_INET;

s_addr.sin_port=htons(PORT);

if(bind(s_socket,(struct sockaddr*)&s_addr,sizeof(s_addr))==-1){

printf("Can not Bind\n");

return -1;

}


if(listen(s_socket,5)==-1){

printf("listen Fail\n");

return -1;

}


while(1){

len = sizeof(c_addr);

c_socket=accept(s_socket,(struct sockaddr*) &c_addr,&len);

length = 0;

temp = rBuffer;

while((n=read(c_socket,temp,1))>0){

if(*temp == '\r')continue;

if(*temp == '\n')break;

if(*temp == '\0')break;

if(length == BUFSIZ) break;

temp++;length++;

}


rBuffer[length]='\0';


if(!strcmp(rBuffer,"ls")){

if((dp=opendir("."))==NULL){

write(c_socket,err_1,strlen(err_1));

}else{

while((dir=readdir(dp))!=NULL){

if(dir->d_ino ==0)continue;

write(c_socket,dir->d_name,strlen(dir->d_name));

write(c_socket," ",1);

}

closedir(dp);

}

}

close(c_socket);

}

close(s_socket);

}



host 부분에서 서버를 열어주고 ,클라이언트쪽에서 서버를 열고 ls 명령을 실행해주면

[gate@localhost gate]$ telnet 127.0.0.1 9080

Trying 127.0.0.1...

Connected to 127.0.0.1.

Escape character is '^]'.

ls

. .. .emacs .bash_logout .bash_profile .bashrc .screenrc gremlin gremlin.c .bash_history hello_server hello_server.c hello_client hello_client.c hello_ext_cliet hello_ext_server.c hello_ext_cliet.c hello_ext_server ls_server.c list.c ls_server Connection closed by foreign host.

이제 클라이언트를 만들어줄 차례 

반응형

'과거의 컴퓨터 공부 > 소켓 프로그래밍' 카테고리의 다른 글

hello_ext_client.c  (0) 2014.08.29
hello_ext_server.c  (0) 2014.08.29
port 종류  (0) 2014.08.28
Hello client  (0) 2014.08.28
Hello_server.c  (0) 2014.08.27
,