반응형
소켓을 이용해서 응용프로그램과 자료를 읽고 쓸 수있다.
sendbuffer에서 자동적으로 상대 receivebuffer에 보내고 read()를 이용해 전송받은 수신버퍼에서 자료를 가져온다.
Socketpair의 헤더와 예제
#include <sys/types.h>
#include <sys/socket.h>
return=socketpair(int domain,int type,int protocol,int sockp[2]);//return int type
sys/types.h와 sys/socket.h를 포함해야하며 socketpair() int형을 반환하며 호출 성공시 0 실패시 -1을 반환한다. 코드는 두개의 소켓을 생성, 자동으로 연결된다.
int sp[2];
if((socketpair(PF_LOCAL,SOCK_STREAM,0,sp)==0)
printf("호출 성공");
TCP/UDP를 지정해야 하나 싶을테지만 그림과 같이 설명한 메커니즘을 보면 이해가 될 것이다.
사용 예제
#include <stdio.h>
#include <sys/socket.h>
#include <string.h>
#include <unistd.h>
int main()
{
int sp[2],result;
char buf[BUFSIZ],data[]="data";
result=socketpair(PF_LOCAL,SOCK_STREAM,0,sp);
if(write(sp[0],data,strlen(data+1));
printf("orgin data:%s\n",data);
if(read(sp[1],buf,BUFSIZ));
printf("received data:%s\n",data);
close(sp[0]);
close(sp[1]);
ruturn 0;
}
sp[0],sp[1] 소켓생성, write에서 sp[1]로 전송(자동), sp[1]은 수신 버퍼를 읽어냄 아래 결과를 보면 sp[0],[1]을 생성한 후, 각각의 소켓을 가리키는 소켓 기술자를 저장해서 반환한다. write함수를 쓰면 sp[1]이 문자열 data를 전송 받았음을 볼 수 있다. 반대로 별도의 연결 과정 없이 sp[1]이 송신 sp[0]이 자료를 수신 받을 수 있다.
더보기
참조문헌
정석용의 TCP/IP 소켓프로그래밍 .정석용
728x90
반응형
'Programming > Socket' 카테고리의 다른 글
[C/C++/소켓프로그래밍] Socket이란? (0) | 2021.03.13 |
---|---|
[C/C++/소켓프로그래밍] Hostent란? (0) | 2021.03.12 |
[C/C++/소켓 프로그래밍] IP 주소 형식 변환 aton() ntoa() 이진형식으로의 변환 (0) | 2021.03.10 |
[C/C++/소켓프로그래밍]hton ntoh (htons,htonl,ntohs,ntohl) 빅 엔디안과 리틀 엔디안 변환 (0) | 2021.03.06 |
PF_INET과 AF_INET (0) | 2021.03.03 |
댓글