기본 콘텐츠로 건너뛰기

라벨이 socket인 게시물 표시

소켓 접속 정보가 문자열일 경우...getaddrinfo

http://www.purewell.biz:80/index.html 같은 주소를 볼 때, 호스트 주소는 www.purewell.biz, 서비스(포트번호)는 80이다. 이것을 이용하여 접속을 위해 struct sockaddr_in 구조체를 만들 때, 번잡스럽게 atoi와 hton?함수를 쓸 것인가... 아직 눈앞에 닥치지는 않았지만, IPv6도 해결하고 싶은데... 그럴 때를 위해 getaddrinfo 함수를 준비하였다. #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> int connect(const char* host, const char* port) { struct addrinfo hints, *res, *ressave; int sock, ret; memset(&hints, 0x00, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if ( 0 != (ret = getaddrinfo(host, port, &hints, &res)) ) { fprintf(stderr, "%s", gai_strerror(ret)); return -1; } ressave = res; do { sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol); if ( -1 == sock ) { continue; } if ( 0 == connect(sock, res->ai_addr, res->ai_addrlen) ) { break; ...

소켓을 통해 다른 프로세스에 FD를 넘겨보자!

Windows에서 되는지 실행 안 해봤고, 단순히 UNIX Network Programming(이하 UNP)에 나온 걸 정리해보겠다. MSDN에는 WSASendMsg 라는 녀석을 준비하였는데 대충 비슷하게 보인다. 다만 Overlapped I/O 를 Windows용으로 써야하기때문에 API가 다른 것 같다. socket에는 sendmsg/recvmsg라는 녀석이 있다. 이 녀석 형태를 보면 아래와 같다. ssize_t sendmsg(int s, const struct msghdr *msg, int flags); ssize_t recvmsg(int s, struct msghdr *msg, int flags); send/recv와 달리 버퍼가 안 보이고, msghdr 라는 구조체를 쓰는데 - 물론 이 녀석이 버퍼겠지 - 이걸 우선 까보자. struct msghdr {     void         * msg_name;     // 접속할 주소     socklen_t    msg_namelen;    // 접속할 주소 크기     struct iovec * msg_iov;      // IO 버퍼     size_t       msg_iovlen;     // IO 버퍼 개수     void         * msg_control;  // 제어 정보 버퍼     socklen_t    msg_controlle...

socketpair

socketpair는 IPC 가운데 하나로 보통 부모 자식 간의 대화를 전달할 때 쓴다고 한다. 얘도 pipe처럼 두개 file-descriptor를 던져주는데, pipe와 달리 두 file-descriptor가 모두 읽기/쓰기가 가능하다. 아래는 예제이다. #include <sys/types.h> #include <sys/socket.h> #include <iostream> #include <errno.h> #include <sys/wait.h> using namespace std; int main(int,char**) {     int s[2];     if ( -1 == socketpair (AF_UNIX, SOCK_STREAM, AF_LOCAL,s) )     {         cout << strerror(errno) << endl;         return 1;     }     char buf[1024];     if ( fork() )     {         strcpy(buf, "Hello, world!");         send(s[0], buf, strlen(buf)+1, 0);         int res;         wait(&res);     }   ...