ossrs / srs

SRS is a simple, high-efficiency, real-time media server supporting RTMP, WebRTC, HLS, HTTP-FLV, HTTP-TS, SRT, MPEG-DASH, and GB28181.
https://ossrs.io
MIT License
25.68k stars 5.38k forks source link

Support none-blocking DNS resolve. #2112

Closed JalySN closed 1 year ago

JalySN commented 3 years ago

srs_tcp_connect is a modification I made, what do you think, esteemed author?

#include "res.c"
srs_error_t srs_tcp_connect(string server, int port, srs_utime_t tm, srs_netfd_t* pstfd)
{
    st_utime_t timeout = ST_UTIME_NO_TIMEOUT;
    if (tm != SRS_UTIME_NO_TIMEOUT) {
        timeout = tm;
    }

    *pstfd = NULL;
    srs_netfd_t stfd = NULL;
/*
    char sport[8];
    snprintf(sport, sizeof(sport), "%d", port);

    addrinfo hints;
    memset(&hints, 0, sizeof(hints));
    hints.ai_family   = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;

    addrinfo* r  = NULL;
    SrsAutoFree(addrinfo, r);
    if(getaddrinfo(server.c_str(), sport, (const addrinfo*)&hints, &r)) {
        return srs_error_new(ERROR_SYSTEM_IP_INVALID, "get address info");
    }
    int sock = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
    if(sock == -1){
        return srs_error_new(ERROR_SOCKET_CREATE, "create socket");
    }
*/
    struct in_addr addr;
    if (dns_getaddr(server.c_str(), &addr, timeout) < 0) {
        return srs_error_new(ERROR_SYSTEM_IP_INVALID, "get address info");
    }
    uint32_t uiIP;
    memcpy(&uiIP, &addr, 4);
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if(sock == -1) {
        return srs_error_new(ERROR_SOCKET_CREATE, "create socket");
    }
    stfd = st_netfd_open_socket(sock);
    if(stfd == NULL){
        ::close(sock);
        return srs_error_new(ERROR_ST_OPEN_SOCKET, "open socket");
    }
    struct sockaddr_in address;
    memset(&address, 0, sizeof(address));
    address.sin_family      = AF_INET;
    address.sin_addr.s_addr = uiIP;
    address.sin_port        = htons(port);
    if (st_connect((st_netfd_t)stfd, (struct sockaddr*)&address, sizeof(address), timeout) == -1){
        srs_close_stfd(stfd);
        return srs_error_new(ERROR_ST_CONNECT, "connect to %s:%d", server.c_str(), port);
    }

    *pstfd = stfd;
    return srs_success;
}
winlinvip commented 3 years ago

Yes, you're right, would you like to submit a patch?

winlinvip commented 3 years ago

It would be best if it could equivalently replace the system's getaddrinfo function, as it would be more convenient to use and is used in many places.