기본 콘텐츠로 건너뛰기

소켓 접속 정보가 문자열일 경우...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;
        }

        close(sock);
        sock = -1;
    } while ( NULL != (res = res->ai_next) );

    freeaddrinfo(ressave);

    if ( !res )
    {
        return -1;
    }

    return sock;
}

댓글

이 블로그의 인기 게시물

Winget 해시 무시하기

가끔씩 Winget 에서 패키지를 다운로드 했을 때, "설치 관리자 해시가 일치하지 않습니다." 오류가 뜰 때가 있다. 보안 이슈가 있지만, 그냥 무시하고 싶을 때, 아래 순서로 무시해준다. 관리자 권한 winget settings --enable InstallerHashOverride 설치 winget install --ignore-security-hash --id NirSoft.NirCmd