1

我在这里有一些代码可以查询Steam主服务器以获取游戏服务器的 IP 列表:

#define _BSD_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <errno.h>
#include <unistd.h>
#include <getopt.h>
#include <sys/types.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>

struct timeval timeout = {1, 0};
char master[256];
char reply[1500];
uint16_t port;
uint8_t query[] = {0x31, 0x03, 0x30, 0x2e, 0x30, 0x2e, 0x30, 0x2e, 0x30, 0x2e,
                         0x30, 0x3a, 0x30, 0x00, 0x00};
uint8_t replyHeader[] = {0xff, 0xff, 0xff, 0xff, 0x66, 0x0a};
int gotResponse = 0;
int bytesRead = 0;
int verbosity = 0;

int main(int argc, char** argv)
{
    strcpy(master, "hl2master.steampowered.com");
    port = 27011;

    int opt;

    while ((opt = getopt(argc, argv, "s:p:v")) != -1)
    {
        switch (opt)
        {
            case 's':
                strcpy(master, optarg);
                break;
            case 'p':
                port = atoi(optarg);
                break;
            case 'v':
                verbosity++;
                break;
        }
    }

    int sockFD;
    struct sockaddr_in server;
    struct hostent* hostInfo;

    sockFD = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);

    if (sockFD == -1)
    {
        perror("socket");
        exit(EXIT_FAILURE);
    }

    if ((setsockopt(sockFD, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)))
         != 0)
    {
        perror("setsockopt");
        exit(EXIT_FAILURE);
    }

    if ((setsockopt(sockFD, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)))
         != 0)
    {
        perror("setsockopt");
        exit(EXIT_FAILURE);
    }

    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    hostInfo = gethostbyname(master);

    if (hostInfo == NULL)
    {
        fprintf(stderr, "Unknown host %s\n", master);
        exit(EXIT_FAILURE);
    }

    server.sin_addr = *(struct in_addr*) hostInfo->h_addr_list[0];

    while (gotResponse == 0)
    {
        if ((sendto(sockFD, query, 15, 0, (struct sockaddr*) &server,
                        sizeof(server))) == -1)
        {
            perror("sendto");
            exit(EXIT_FAILURE);
        }

        socklen_t serverSize = sizeof(server);

        if ((bytesRead = recvfrom(sockFD, reply, 1500, 0,
                                          (struct sockaddr*) &server, &serverSize)) == -1)
        {
            if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
            {
                fprintf(stderr, "TIMEOUT\n");
            }
            else
            {
                perror("recvfrom");
                exit(EXIT_FAILURE);
            }
        }
        else
            gotResponse = 1;
    }

    if ((close(sockFD)) == -1)
    {
        perror("close");
        exit(EXIT_FAILURE);
    }

    if ((strncmp(reply, replyHeader, 6)) != 0)
    {
        fprintf(stderr, "Bad reply from master server\n");
        exit(EXIT_FAILURE);
    }

    uint32_t i = 6;

    while (i < bytesRead)
    {
        if (verbosity > 0)
            fprintf(stderr, "%u <= %d\n", i, bytesRead);

        uint8_t ip[4] = {reply[i], reply[i + 1], reply[i + 2], reply[i + 3]};

        printf("%hu.%hu.%hu.%hu:", ip[0], ip[1], ip[2], ip[3]);

        uint16_t thisPort = reply[i + 4] + (reply[i + 5] << 8);

        printf("%hu\n", ntohs(thisPort));

        i += 6;
    }

    return EXIT_SUCCESS;
}

(注意一秒钟timeout。)

除了一些奇怪的通信行为之外,这很好。它似乎要么第一次工作,要么一次又一次地不断超时,而且永远不会成功。

修复的方法是简单地再次运行它,它可能会起作用,但我不明白它任意不起作用的原因。

任何输入将不胜感激!

4

5 回答 5

3

The host hl2master.steampowered.com resolves to three IP addresses:

syzdek@blackenhawk$ dig +short hl2master.steampowered.com
63.234.149.83
63.234.149.90
72.165.61.153
syzdek@blackenhawk$

Two of the three IP address are responding to queries, the third is not:

syzdek@blackenhawk$ ./a.out -s 63.234.149.83 |head -2
66.189.187.173:27012
216.6.229.173:27015
syzdek@blackenhawk$ ./a.out -s 63.234.149.90 |head -2
66.189.187.173:27012
216.6.229.173:27015
syzdek@blackenhawk$ ./a.out -s 72.165.61.153
recvfrom: TIMEOUT: Resource temporarily unavailable
recvfrom: TIMEOUT: Resource temporarily unavailable
^C
syzdek@blackenhawk$

Small note, I changed fprintf(stderr, "TIMEOUT\n"); to perror("recvfrom: TIMEOUT"); in the course of trying your code.

Maybe try a using a different server after the timeout:

int retryCount = 0;
while (gotResponse == 0)
{
    // verify that next address exists
    if (hostInfo->h_addr_list[retryCount/2] == NULL)
    {
        fprintf(stderr, "All servers are not responding.");
        exit(EXIT_FAILURE);
    };

    // Attempt each address twice before moving to next IP address
    server.sin_addr = *(struct in_addr*) hostInfo->h_addr_list[retryCount/2];
    retryCount++;

    if ((sendto(sockFD, query, 15, 0, (struct sockaddr*) &server,
                            sizeof(server))) == -1)
    {
        perror("sendto");
        exit(EXIT_FAILURE);
    }

    / * rest of code */

The above edits will try each address returned by gethostbyame() twice before moving to the next returned IP address.

于 2011-10-20T16:38:32.967 回答
3

由于您发布了整个可运行代码,因此我尝试按照 cdleonard 的建议使用 strace 运行它。这立即表明,每次程序运行时,gethostbyname对于 for 的调用都会返回两个不同地址中的一个 - 要么 -要么- 当第一个地址返回时它工作正常,而第二个地址因超时而失败。hl2master.steampowered.com63.234.149.8372.165.61.153

所以问题似乎是DNS上有两个服务器地址,但其中一个并没有真正起作用。

我建议检查 gethostbyaddr 返回的 h_addr_list 并在循环中依次检查每个地址,而不是总是发送到第一个地址。

于 2011-10-20T16:25:02.910 回答
3

只是一个疯狂的猜测:也许 recvfrom 正在破坏服务器参数,并且以下发送的地址不正确?尝试传递一个单独的 struct sockaddr。

strace 输出可能会有所帮助。

于 2011-10-20T16:06:09.747 回答
1

如果您EAGAIN从呼叫recvfrom()中得到“资源暂时不可用”,您可以尝试重新呼叫gethostbyname(),以防 DNS 可能为您传递的主机名提供不同的 IP(以循环方式)。

如果是这种情况,并且至少有一个 DNS 返回的地址不可访问,那么您将遇到您所面临的行为。

就像一个注释:gethostbyname()可能会返回静态数据,所以复制结果而不只是引用它是个好主意。

于 2011-10-20T16:24:18.393 回答
0

代替gethostbyname()只返回一个 IP 地址的 ,您可以尝试使用getaddrinfo(),它为您提供所有 IP 地址,甚至提供所有受支持的地址系列。

这是它的工作原理:

    int sockFD;
    struct hostent* hostInfo;

    struct addrinfo hints = {
        .ai_socktype = SOCK_DGRAM,
        .ai_protocol = IPPROTO_UDP /* MHO redundant*/
    };
    struct addrinfo * ai_chain, *ai;

    int gai_ret = getaddrinfo(master, NULL, &hints, &ai_chain);
    if (gai_ret != 0) {
        fprintf(stderr, "getaddrinfo: %s", gai_strerror(gai_ret));
        exit(EXIT_FAILURE);
    }

    for (ai = ai_chain; ai; ai = ai->ai_next) {
        printf("try %s\n", ai->ai_canonname ? ai->ai_canonname : "");
        sockFD = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
        if (sockFD == -1)
        {
            perror("socket");
            continue;
        }

        if ((setsockopt(sockFD, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout))) != 0)
        {
            perror("setsockopt 1");
            continue;
        }

        if ((setsockopt(sockFD, SOL_SOCKET, SO_SNDTIMEO, &timeout,
    sizeof(timeout)))
            != 0)
        {
            perror("setsockopt 2");
            continue;
        }

        if ((sendto(sockFD, query, 15, 0, ai->ai_addr, ai->ai_addrlen)) == -1)
        {
            perror("sendto");
            continue;
        }

        struct sockaddr_in6 server;
        socklen_t serverSize = sizeof(server);

        if ((bytesRead = recvfrom(sockFD, reply, 1500, 0,
                                        (struct sockaddr*) &server,
&serverSize)) == -1)
        {
            if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
            {
                fprintf(stderr, "TIMEOUT\n");
                continue;
            }
            else
            {
                perror("recvfrom");
                continue;
            }
        }
        else
            break;
    }

    if ((close(sockFD)) == -1)
    {
        perror("close");
        exit(EXIT_FAILURE);
    }

    if ((strncmp(reply, replyHeader, 6)) != 0)
    {
        fprintf(stderr, "Bad reply from master server\n");
        exit(EXIT_FAILURE);
    }

    uint32_t i = 6;

    while (i < bytesRead)
    {
        if (verbosity > 0)
            fprintf(stderr, "%u <= %d\n", i, bytesRead);

        uint8_t ip[4] = {reply[i], reply[i + 1], reply[i + 2], reply[i + 3]};

        printf("%hu.%hu.%hu.%hu:", ip[0], ip[1], ip[2], ip[3]);

        uint16_t thisPort = reply[i + 4] + (reply[i + 5] << 8);

        printf("%hu\n", ntohs(thisPort));

        i += 6;
    }

    return EXIT_SUCCESS;
}

虽然代码仍然存在一个或其他缺陷(直到现在,它从不关闭套接字;缓冲区溢出漏洞是master由于strcpy()而不是strncpy()),它向您展示了事情是如何工作的。

于 2011-10-20T21:13:16.323 回答