리눅스는 소켓을 파일의 일종으로 구분
리눅스에서 독립적으로 제공하는 함수를 통해 소켓을 데이터 송수신에 사용 가능
파일 디스크립터를 인자로 하여 입출력을 진행
- 파일 디스크립터: 시스템으로부터 할당 받은 파일 또는 소켓에 부여된 정수
파일 입출력 함수
파일 열기
#include <sys/types.h>
#include <sys/stat.h>
#include <fcnt1.h>
int open(const char *path, int flag);
- 성공 시 파일 디스크립터, 실패 시 -1 리턴
파일 닫기
#include <unistd.h>
int close(int fd);
- 성공 시 0, 실패 시 -1 리턴
파일에 데이터 쓰기
#include <unistd.h>
ssize_t write(int fd, const void * buf, size_t nbytes);
- 성공 시 전달한 바이트 수, 실패 시 -1 리턴
파일에 저장된 데이터 읽기
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t nbytes);
- 성공 시 수신한 바이트 수, 실패 시 -1 리턴
파일 디스크립터와 소켓
#include <stdio.h>
#include <fcnt1.h>
#include <unistd.h>
#include <sys/socket.h>
int main() {
int fd1, fd2, fd3;
fd1 = socket(PF_INET, SOCK_STREAM, 0);
fd2 = open("test.dat", O_CREAT|O_WORNLY|O_TRUNC);
fd3 = socket(PF_INET, SOCK_DGRAM, 0);
printf("file descriptor 1: %d\n", fd1);
printf("file descriptor 2: %d\n", fd2);
printf("file descriptor 3: %d\n", fd3);
close(fd1);
close(fd2);
close(fd3);
return 0;
}
'개인 공부 > 네트워크' 카테고리의 다른 글
[Chapter 03-2] 주소정보의 표현 (0) | 2023.07.20 |
---|---|
[Chapter 02-2] 윈도우 기반에서 이해 및 확인하기 (0) | 2023.07.06 |
[Chapter 02-1] 소켓의 프로토콜과 그에 따른 데이터 전송 특성 (0) | 2023.07.06 |
[Chapter 01-3] 윈도우 기반으로 구현 (0) | 2023.07.05 |
[Chapter 01-1] 네트워크 프로그래밍과 소켓의 이해 (0) | 2023.07.03 |