์ค๋์ ์ฝ์น๋์ด ์ฌ๋ ค์ค https://youtu.be/LtXEMwSG5-8 ์์์ ๋ณด๊ณ ๋ฐ๋ผํด๋ณด๊ณ , ์ ๋ฆฌํด์ ์ฑ ๊ณผ ์กฐ๊ธ ๋ค๋ฅธ ์คํ์ผ์ ์ฝ๋๋ฅผ ๊ณต๋ถํด ๋ณด์๋ค.
ํด๋น ๊ฐ์๋ ์๋ ์ฝ๋์ include๋์ด์๋ ํค๋ํ์ผ ํจ์๋ค์ ์ด์ฉํด socket ํต์ ์ ๊ตฌํํ๋ ๋ฐฉ๋ฒ์ด๋ค.
์ฌ์ค ์ฐ๋ฆฌ๊ฐ proxy.lab์์ ์ฌ์ฉํ๋ ๊ธฐ๋ฅ๋ค๋ csapp.hํ์ผ์ ๊ฐ๋ณด๋ฉด ๋ชจ๋ include๋์ด ์๋ค.
ํ์ง๋ง, ์ค๋ฅ๊ฐ ๋๋ฉด ๋ฐ๋ก ์๋ฒ๊ฐ ๊บผ์ง๋ ๊ฒ์ ๋ง๊ธฐ์ํด ํจ์๋ก ํ์ธต ๊ฐ์๋๊ณ ์ฌ์ฉํ๋๋ก ๋์ด์๋ค.
ํด๋น๋ฐฉ๋ฒ์ ์ฝ๋๋ค์ด ์ง๊ด์ ์ด๋ง, ์ด์ ๋๊น์ง๋ง ๊ณต๋ถํ๊ณ , ๋ค์ proxy.c๋ฅผ ๊ตฌํํ๋ฌ๊ฐ์ผ๊ฒ ๋ค.
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main(){
// create a socket
int network_socket;
/* socket์
param1: domain of the socket, header file์ ๋ญ๋ผ๊ณ ๋ถ๋ฅผ ๊ฑด์ง ,
param2: type of the socket(TCP or UDP)
param3: ํน๋ณํ ํ๋กํ ์ฝ์ ์ฐ๊ณ ์ถ์ ๋, ์ฐ๋ฆฌ๋ TCP default๋ฅผ ์ธ๊ฑฐ๋ผ 0*/
network_socket = socket(AF_INET, SOCK_STREAM, 0);
// specify an address for the socket
struct sockaddr_in server_address;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(9002); //์ฐ๋ฆฌ๊ฐ ์ฐ๊ฒฐํด์ค์ผํ ํน์ ํฌํธ specify. htons()๋ conversion funt: intger port-> network byte order
server_address.sin_addr.s_addr = INADDR_ANY; // ์๋ฒ๊ฐ ๋ฐ์ธ๋ฉํ IP ์ฃผ์. ์ด ๊ฐ์ 0, ์๋ฒ๊ฐ ๋ชจ๋ IP ์ฃผ์๋ฅผ ์ฌ์ฉํ์ฌ ๋ค์ด์ค๋ ์ฐ๊ฒฐ ์์ฒญ์ ๋ฐ์๋ค์ด๋๋ก.
// 0์ด๋ฉด ok
int connection_status = connect(network_socket, (struct sockaddr *) &server_address, sizeof(server_address));
//check for error with the connection
if (connection_status == -1){
printf("There was an error making a connection to the remote socket \n\n");
}
//receive data from the server
char server_response[256];
recv(network_socket, &server_response, sizeof(server_response), 0);
//print out the server's response
printf("The server sent the data: %s\n", server_response);
//and then close the socket
close(network_socket);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main(){
char server_message[256] = "You have reached the server!";
//socket ์์ฑ
int server_socket;
server_socket = socket(AF_INET, SOCK_STREAM, 0);
//address struct ์ ์
struct sockaddr_in server_address;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(9002);
server_address.sin_addr.s_addr = INADDR_ANY;
//socket์ ํน์ IP์ Port์ binding
bind(server_socket, (struct sockaddr*) &server_address, sizeof(server_address));
//listen ์์ผ ๋ง๋ค๊ธฐ
listen(server_socket, 5);
//accept ์์ผ ๋ง๋ค๊ธฐ data ์๋ค๊ฐ๋คํ๋ ์์ผ
int client_socket;
client_socket = accept(server_socket, NULL, NULL);
//๋ฉ์ธ์ง ๋ณด๋ด๊ธฐ
send(client_socket, server_message, sizeof(server_message), 0);
//์์ผ ๋ซ๊ธฐ
close(server_socket);
return 0;
}