소개
간단한 TCP 서버 및 클라이언트와 비교하여, 이 글의 서버 및 클라이언트 프로그램은 다음과 같은 점이 개선되었습니다:
inet_ntop()함수를 사용하여 서버 프로그램이 IPv4 및 IPv6 주소를 올바르게 처리할 수 있습니다.getaddrinfo()함수를 사용하여 서버 프로그램이 IPv4 및 IPv6 주소를 올바르게 처리할 수 있습니다.fork()함수를 사용하여 서버 프로그램이 여러 클라이언트의 연결 요청을 동시에 처리할 수 있습니다.waitpid()함수를 사용하여 서버 프로그램이 자식 프로세스의 종료를 올바르게 처리할 수 있습니다.
서버 코드
CodeBlock Loading...
클라이언트 코드
C
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define PORT "43866" /* 포트 번호 */
#define MAXDATASIZE 100 /* 최대 데이터 전송량 */
/* sockaddr 가져오기, IPv4 또는 IPv6: */
void *get_in_addr(struct sockaddr *sa)
{
/* 주소 체계 확인 */
if (sa->sa_family == AF_INET)
{
/* IPv4 주소 반환 */
return &(((struct sockaddr_in *)sa)->sin_addr);
}
/* IPv6 주소 반환 */
return &(((struct sockaddr_in6 *)sa)->sin6_addr);
}
int main(int argc, char *argv[])
{
int sockfd; /* sockfd: socket() 함수의 반환값 저장 */
char buf[MAXDATASIZE]; /* 버퍼, 수신 데이터 저장 */
struct addrinfo hints, *servinfo, *p; /* hints: addrinfo 구조체 설정용, servinfo: 주소 정보 저장, p: servinfo 순회용 addrinfo 포인터 */
int rv; /* getaddrinfo() 함수의 반환값 저장 */
char s[INET6_ADDRSTRLEN]; /* inet_ntop() 함수가 반환한 주소 정보 문자열 저장 */
int numbytes_recv; /* recv() 함수의 반환값 저장 */
int numbytes_send; /* send() 함수의 반환값 저장 */
/* 인자 개수 확인 */
if (argc != 2)
{
fprintf(stderr, "usage: ./client hostname\n");
exit(1);
}
/* hints 구조체 초기화 */
memset(&hints, 0, sizeof hints);
/* hints 구조체 설정 */
hints.ai_family = AF_UNSPEC; /* IPv4 또는 IPv6 미지정 */
hints.ai_socktype = SOCK_STREAM; /* TCP 스트림 소켓 */
/* 주소 정보 가져오기 */
if ((rv = getaddrinfo(argv[1], PORT, &hints, &servinfo)) != 0)
{
/* 오류 메시지 출력 */
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
/* servinfo 구조체 링크드 리스트 순회 */
for (p = servinfo; p != NULL; p = p->ai_next)
{
/* 소켓 생성 */
if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
{
/* 오류 메시지 출력 */
perror("client: socket");
continue;
}
/* 서버 연결 */
if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1)
{
/* 서버 연결 실패 */
close(sockfd);
perror("client: connect");
continue;
}
break;
}
/* servinfo 구조체를 모두 순회했으나 연결 성공하지 못함 */
if (p == NULL)
{
fprintf(stderr, "client: failed to connect to server\n"); /* 서버로 데이터 전송 */
return 2;
}
/* 주소 정보를 문자열로 변환 */
inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), s, sizeof s);
/* 연결된 서버의 주소 정보 출력 */
printf("client: connecting to %s port %s\n", s, PORT);
/* servinfo 구조체 해제 */
freeaddrinfo(servinfo);
/* 데이터 수신 */
if ((numbytes_recv = recv(sockfd, buf, MAXDATASIZE - 1, 0)) == -1)
{
/* 데이터 수신 실패 */
perror("recv");
exit(1);
}
/* 문자열 종료자 추가 */
buf[numbytes_recv] = '\0';
/* 수신 데이터 출력 */
printf("client: received '%s' from server.\n", buf);
/* 전송할 데이터 구성 */
char *msg = "Hello world from client!";
int msg_len = strlen(msg);
/* 서버로 데이터 전송 */
if ((numbytes_send = send(sockfd, msg, msg_len, 0)) == -1)
{
/* 데이터 전송 실패 */
perror("send");
}
printf("client: sent '%s' (%d bytes) to server.\n", msg, numbytes_send);
/* 소켓 닫기 */
close(sockfd);
printf("client: closed socketfd %d.\n", sockfd);
return 0;
}
/* 참고: 31-33쪽, Beej's Guide to Network Programming Using Internet Sockets */
컴파일
BASH
gcc server.c -o server
gcc client.c -o client
실행 및 출력
CodeBlock Loading...
CodeBlock Loading...
서버 실행 전에 클라이언트를 실행하면 다음과 같은 오류 메시지가 출력됩니다:
BASH
$ ./client localhost
client: connect: Connection refused
client: failed to connect to server