반응형
Client에서 간단하게 Text를 아래처럼 보낼 수 있습니다.(nc 활용)
echo "My Text" | timeout 1 nc IP_ADDR 12345
이걸 서버에서 받아서 프린트하고 저장하는 프로그램
나의 말:
ChatGPT의 말:
ChatGPT 복붙하면 코드가 라이별로 안나와서 이렇게......
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <time.h>
#define PORT 12345
#define BUFFER_SIZE 1024
#define LOG_FILE "/tmp/log.server_list"
int main() {
int server_fd, client_fd;
struct sockaddr_in server_addr, client_addr;
socklen_t client_addr_len = sizeof(client_addr);
char buffer[BUFFER_SIZE];
char client_ip[INET_ADDRSTRLEN];
// 소켓 생성
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("소켓 생성 실패");
exit(EXIT_FAILURE);
}
// 서버 주소 구조체 설정
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(PORT);
// 소켓 바인딩
if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
perror("바인딩 실패");
close(server_fd);
exit(EXIT_FAILURE);
}
// 연결 대기
if (listen(server_fd, 3) == -1) {
perror("연결 대기 실패");
close(server_fd);
exit(EXIT_FAILURE);
}
printf("서버가 포트 %d에서 대기 중...\n", PORT);
while (1) {
// 연결 수락
if ((client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &client_addr_len)) == -1) {
perror("연결 수락 실패");
continue;
}
// 클라이언트 IP 주소 변환
inet_ntop(AF_INET, &client_addr.sin_addr, client_ip, INET_ADDRSTRLEN);
printf("클라이언트 연결됨: %s\n", client_ip);
// 로그 파일 열기 (추가 모드)
FILE *log_file = fopen(LOG_FILE, "a");
if (log_file == NULL) {
perror("로그 파일 열기 실패");
close(client_fd);
continue;
}
// 데이터 수신 및 출력
ssize_t bytes_received;
while ((bytes_received = recv(client_fd, buffer, BUFFER_SIZE - 1, 0)) > 0) {
buffer[bytes_received] = '\0';
// 현재 시간 가져오기
time_t now = time(NULL);
struct tm *local_time = localtime(&now);
char time_str[20];
strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", local_time);
// 콘솔에 출력
printf("[%s] 클라이언트(%s): %s\n", time_str, client_ip, buffer);
// 로그 파일에 저장
fprintf(log_file, "[%s] 클라이언트(%s): %s\n", time_str, client_ip, buffer);
fflush(log_file); // 버퍼 비우기
}
if (bytes_received == -1) {
perror("데이터 수신 실패");
} else {
printf("클라이언트(%s) 연결 종료\n", client_ip);
}
// 로그 파일 닫기
fclose(log_file);
// 소켓 닫기
close(client_fd);
}
close(server_fd);
return 0;
}
반응형
'ChatGPT > 프로...Linux' 카테고리의 다른 글
하나의 IP에 두개의 인터페이스 이름을 만드는 방법 (0) | 2025.04.02 |
---|---|
Ubuntu) 한국 표준시(KST)인 Asia/Seoul로 변경 (0) | 2025.04.02 |
프로세스 <defunct> 처리(SIGCHLD 처리) (0) | 2025.04.02 |
Core Dump (0) | 2025.04.02 |
[JSON] upload후 항목별 표시 (0) | 2025.03.04 |