本文介绍了如何连接到IRC频道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Hi Code项目,
我正在编写一个连接到IRC频道并读出消息的简单程序。请解释一下我该如何做到这一点?
我可以编写一个连接到主机但不能连接到Web服务器或IRC服务器的程序o你看到了问题。 />
先谢谢。
Hi Code project,
I am coding a simple program which connects to a IRC channel and reads out messages. Please explain how i can do that ?
I can code a program which connects to a host but not to web servers or IRC servers o you see the problem.
Thanks in advance.
#include <iostream>
#include <winsock2.h>
#include <string>
#include <cstring>
#include <fstream>
#pragma comment(lib, "ws2_32.lib")
using namespace std;
unsigned long resolveHost(const string &host){
LPHOSTENT entryHost = gethostbyname(host.c_str());
if(!entryHost){
unsigned int addr = inet_addr(host.c_str());
entryHost = gethostbyaddr((char*)&addr, 4, AF_INET);
if(!entryHost) return 0;
}
return *((int*)*entryHost->h_addr_list);
}
int main(){
WSADATA wsaData;
SOCKADDR_IN saddr;
SOCKET sock;
char buffer[1024*8] = {"0"};
string adres_hosta = "irc.example.com";
string sbuffer;
string nick = "johnsmith";
string kanal = "#channel";
string password = "p@55w0rd";
string auth = "/AuthServ auth johnsmith p@55w0rd";
WSAStartup(MAKEWORD(2, 2), &wsaData);
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
saddr.sin_addr.S_un.S_addr = resolveHost(adres_hosta);
saddr.sin_port = htons(6667);
saddr.sin_family = AF_INET;
if(connect(sock, (sockaddr*)&saddr, sizeof(sockaddr)) == SOCKET_ERROR){
cout << "Failed" << adres_hosta << ".";
return 0;
}
recv(sock, buffer, 1024*8, 0);
cout << buffer << endl << endl << flush;
/*
1. Pass message
2. Nick message
3. User message
*/
sbuffer ="PASS " + password + "\r\n";
send(sock, sbuffer.c_str(), strlen(sbuffer.c_str()), 0);
recv(sock, buffer, 1024*8, 0);
cout << sbuffer.c_str() << endl << buffer << endl << endl;
sbuffer = "NICK " + nick + "\r\n";
send(sock, sbuffer.c_str(), strlen(sbuffer.c_str()), 0);
recv(sock, buffer, 1024*8, 0);
cout << sbuffer.c_str() << endl << buffer << endl << endl;
sbuffer = "USER " + nick + " " + adres_hosta + " " + nick + " :" + nick + "\r\n";
send(sock, sbuffer.c_str(), strlen(sbuffer.c_str()), 0);
recv(sock, buffer, 1024*8, 0);
cout << sbuffer.c_str() << endl << buffer << endl << endl;
sbuffer = "JOIN " + kanal + "\r\n";
send(sock, sbuffer.c_str(), strlen(sbuffer.c_str()), 0);
recv(sock, buffer, 1024*8, 0);
cout << sbuffer.c_str() << endl << buffer << endl << endl;
while(true){
recv(sock, buffer, 1024*8, 0);
cout << buffer << endl << endl;
if(buffer[0] == 'PING'){
sbuffer = "PONG :" + adres_hosta + "\r\n";
send(sock, sbuffer.c_str(), strlen(sbuffer.c_str()), 0);
cout << sbuffer.c_str() << endl << buffer << endl << endl;
}
}
return 1;
}
推荐答案
这篇关于如何连接到IRC频道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!