hahahia

Linux TCP/IP 소켓 프로그래밍 본문

Linux/Linux Programming

Linux TCP/IP 소켓 프로그래밍

hahahia 2013. 1. 27. 23:45

클라이언트에서 어떠한 문자열을 입력하게되면 서버에서 read하고 다시 클라이언트에 write하게 되어 즉, 클라이언트에서는 자신이 입력한 문자열을 다시 출력하게 되는 구조를 띄게 됩니다.


client.c



#include <stdio.h>

#include <sys/socket.h>

#include <arpa/inet.h>

#include <sys/stat.h>

#include <string.h>

#include <unistd.h>

#include <stdlib.h>

#define MAXLINE 1024


int main(int argc, char **argv)

{

struct sockaddr_in serveraddr;

int server_sockfd;

int client_len;

char buf[MAXLINE];

if((server_sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)

{

perror("error : ");

return 1;

}

serveraddr.sin_family = AF_INET;

serveraddr.sin_addr.s_addr = inet_addr("127.0.0.1");

serveraddr.sin_port = htons(3500);

client_len = sizeof(serveraddr);

if(connect(server_sockfd, (struct sockaddr *)&serveraddr, client_len) == -1)

{

perror("connect error : ");

return 1;

}

memset(buf, 0x00, MAXLINE);

read(0, buf, MAXLINE);

if(write(server_sockfd, buf, MAXLINE) <= 0)

{

perror("write error: " );

return 1;

}

memset(buf, 0x00, MAXLINE);

if(read(server_sockfd, buf, MAXLINE) <= 0)

{

perror("read error : ");

return 1;

}

close(server_sockfd);

printf("server : %s\n", buf);

return 0;

}


server.c


#include <stdio.h>

#include <sys/socket.h>

#include <stdlib.h>

#include <arpa/inet.h>

#include <sys/stat.h>

#include <unistd.h>

#include <string.h>


#define MAXBUF 1024


int main(int argc, char **argv)

{

int server_sockfd, client_sockfd;

int client_len, n;

char buf[MAXBUF];

struct sockaddr_in clientaddr, serveraddr;

if((server_sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1)

{

perror("socket error:");

exit(0);

}

bzero(&serveraddr, sizeof(serveraddr));

serveraddr.sin_family = AF_INET;

serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);

serveraddr.sin_port = htons(atoi(argv[1]));

bind(server_sockfd, (struct sockaddr*)&serveraddr, sizeof(serveraddr));

listen(server_sockfd, 5);


while(1)

{

memset(buf, 0x00, MAXBUF);

client_sockfd = accept(server_sockfd, (struct sockaddr *)&clientaddr, &client_len);

printf("New Client Connect : %s\n", inet_ntoa(clientaddr.sin_addr));

if((n = read(client_sockfd, buf, MAXBUF)) <= 0)

{

close(client_sockfd);

continue;

}

if(write(client_sockfd, buf, MAXBUF) <= 0)

{

perror("write error:");

close(client_sockfd);

}

}

close(server_sockfd);

return 0;

}



client.c


server.c


'Linux > Linux Programming' 카테고리의 다른 글

[TCP/IP] 온라인 사칙연산 서비스 구현  (0) 2013.02.09
Linux Shell 구현  (0) 2013.01.27
Comments