Skip to content

Instantly share code, notes, and snippets.

@yeonwooz
Last active November 9, 2022 06:25
Show Gist options
  • Save yeonwooz/971b928153cfb9f05fafcfa0735fc0ea to your computer and use it in GitHub Desktop.
Save yeonwooz/971b928153cfb9f05fafcfa0735fc0ea to your computer and use it in GitHub Desktop.
multi_thread_proxy
int main(int argc, char **argv) {
int listenfd, *clientfd;
socklen_t clientlen;
struct sockaddr_storage clientaddr;
char client_hostname[MAXLINE], client_port[MAXLINE]; // 프록시가 요청을 받고 응답해줄 클라이언트의 IP, Port
pthread_t tid; // 스레드에 부여할 tid 번호 (unsigned long)
if (argc != 2) {
fprintf(stderr, "usage: %s <port>\n", argv[0]);
exit(0);
}
listenfd = Open_listenfd(argv[1]); // 대기 회선
while (1) {
clientlen = sizeof(struct sockaddr_storage);
clientfd = (int *)Malloc(sizeof(int)); // 여러개의 디스크립터를 만들 것이므로 덮어쓰지 못하도록 고유메모리에 할당
*clientfd = Accept(listenfd, (SA *)&clientaddr, &clientlen); // 프록시가 서버로서 클라이언트와 맺는 파일 디스크립터(소켓 디스크립터) : 고유 식별되는 회선이자 메모리 그 자체
Getnameinfo((SA *)&clientaddr, clientlen, client_hostname, MAXLINE, client_port, MAXLINE, 0);
Pthread_create(&tid, NULL, thread, clientfd); // 프록시가 중개를 시작
}
return 0;
}
void *thread(void *argptr) {
int clientfd = *((int *)argptr);
Pthread_detach((pthread_self()));
Free(argptr);
doit(clientfd);
Close(clientfd);
return NULL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment