C ++ irc​​服务器不发送ping

时间:2019-02-24 14:38:37

标签: c++ sockets protocols irc

我试图用c ++创建一个简单的irc客户端。我正在发送PASS,NICK和USER消息,但服务器未向我发送PING。我无法注册...

这是代码:

#include <iostream>
#include <string>
#include <WS2tcpip.h>

#pragma comment(lib,"ws2_32.lib")


using namespace std;
string ipadress = "91.217.189.58";
int port = 6667;
WSADATA ws_data;
SOCKET Skt;
int main()
{
    int ws_result = WSAStartup(MAKEWORD(2, 2), &ws_data);
    if (ws_result != 0)
        cout << "socket cannot be initialized\n";
    else
        cout << "Soket initialized!\n";

    Skt = socket(AF_INET, SOCK_STREAM, 0);

    if (Skt == INVALID_SOCKET)
        cout << "socket not created\n";
    else
        cout << "Socket created!\n";

    sockaddr_in hint;
    hint.sin_family = AF_INET;
    hint.sin_port = htons(6667);
    inet_pton(AF_INET, ipadress.c_str(), &hint.sin_addr);

    int connection_result = connect(Skt, (sockaddr*)&hint, sizeof(hint));

    if (connection_result == SOCKET_ERROR)
        cout << "Socket could not connect\n";
    else
        cout << "Socket Connected!\n";
    string channel = "JOIN #dikes\r\n";
        string Pass = "PASS PASSRE";
        string user = "USER guest 0 * :IRCbot\r\n";
        string nick = "NICK botzzz\r\n";

        char buffer[4096];//buffer to recieve messages from irc server

        send(Skt, Pass.c_str(), Pass.size(), 0);

        send(Skt, nick.c_str(), nick.size() , 0);

        send(Skt, user.c_str(), user.size(), 0);

        while (true)
        {
            string Pong = "PONG";

            ZeroMemory(buffer, 4096);
            int bytes_recieved = recv(Skt, buffer, 4096, 0);
            string msg = string(buffer, 0, bytes_recieved);
            cout << msg;
            if (msg == "PING")
            {
                send(Skt, Pong.c_str(), Pong.size() + 1, 0);
            }
            else if (msg == "001")
            {
                send(Skt, channel.c_str(), channel.size(), 0);

            }
        }

这是此代码的输出:

Soket initialized!
Socket created!
Socket Connected!
:irc.portlane.se 020 * :Please wait while we process your connection.
ERROR :Closing Link: [unknown@176.43.204.170] (Ping timeout)

1 个答案:

答案 0 :(得分:1)

  1. 您的支票未占\r\n
  2. 您的支票未占the nick parameter on the PING command
  3. 您的PASS命令未被\r\n终止
  4. 您的PONG响应未被\r\n终止
  5. 您已假设“接收的数据”和“线”是一对一的映射。这不能保证。极有可能(甚至可能是)对recv的一次调用用从 zero 许多个完整的命令/消息的数据填充缓冲区。消息不完整!

    TCP / IP不知道IRC协议;它不在乎“命令”的概念,也不会为您将数据包分解为那些逐项列出的内容。您必须这样做。 TCP / IP只是向您发送字节流

    您需要在接收到字节后将其添加到辅助缓冲区中,然后迭代解析该缓冲区以提取所有可用的完整行。 (正确执行此操作,它将同时处理#1)

(但是,我仍然希望在您的输出中看到ping请求,所以其他一些事情也一定是错误的。)