[c언어] 네트워크 연결 및 해제
이번에는 c언어를 활용하여 네트워크 연결과 해제에 대해 알아보겠습니다. 네트워크 연결에 관련된 라이브러리로는 socket.h
가 있으며, netdb.h
는 DNS 관련 함수를 제공합니다.
네트워크 연결
네트워크 연결을 하려면 다음과 같은 단계를 따릅니다.
- 소켓 생성:
socket()
함수를 사용하여 소켓을 생성합니다. - 서버 정보 획득:
getaddrinfo()
함수를 사용하여 서버의 정보를 얻습니다. - 연결 시도:
connect()
함수를 사용하여 서버에 연결을 시도합니다.
다음은 간단한 클라이언트의 예시입니다.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
int main() {
int sockfd;
struct addrinfo hints, *servinfo, *p;
int rv;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if ((rv = getaddrinfo("www.example.com", "http", &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
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;
}
freeaddrinfo(servinfo);
if (p == NULL) {
fprintf(stderr, "client: failed to connect\n");
return 2;
}
close(sockfd);
return 0;
}
네트워크 해제
네트워크 해제를 위해서는 close()
함수를 사용하여 소켓을 닫습니다.
int status = close(sockfd);
if (status == 0) {
printf("Socket closed\n");
} else {
perror("close");
}
이제 c언어를 사용하여 간단한 네트워크 연결 및 해제에 대해 알아보았습니다. 간단한 예시이지만, 실제 프로젝트에서는 더 많은 예외처리와 안정성을 고려해야 합니다.
참고 자료: Beej’s Guide to Network Programming