我试图建立抽搐了聊天机器人完全用C语言。但我有在连接到服务器的问题:irc.chat.twitch.tv
与端口6667
。我打电话gethostbyname()
检索主机的IP地址,但连接功能从来没有建立连接,并返回“连接失败”。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>
#include "Authentication.h"
#include "MessageHandlers.h"
int main()
{
int sock;
struct sockaddr_in addr;
struct hostent * addr_info;
char * ip;
addr_info = gethostbyname("irc.chat.twitch.tv");
ip = inet_ntoa(*(struct in_addr *)addr_info->h_name);
printf("%s", ip);
addr.sin_family = AF_INET;
addr.sin_port = htons(6667);
addr.sin_addr.s_addr = inet_addr(ip);
sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock < 0)
{
fprintf(stderr, "\nSocket Creation Failed\n");
exit(EXIT_FAILURE);
}
printf("\nConnecting to Twitch IRC Server...\n");
if(connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == -1)
{
fprintf(stderr, "\nConnection Failed\n");
exit(EXIT_FAILURE);
}
// SendAuthentication(sock);
/*
while(1)
{
OnMessageEvents(sock);
}
*/
exit(EXIT_SUCCESS);
}
是不是我做错了吗?抽搐解析的IP地址似乎是105.114.99.45
。我搜索在谷歌的实际IP地址,但我没有找到任何答案。
我用nslookup irc.chat.twitch.tv
并尝试了所有的IP地址,但我仍然得到了“连接失败”。
如果我使用telnet irc.chat.twitch.tv 6667
我得到一个连接,我可以进行登录。
解决了上述评论。在struct sockaddr_in
的端口号是网络字节顺序(又名大端),而您的计算机可能运行的小端。要分配它,你必须使用
addr.sin_port = htons(6667);
代替
addr.sin_port = 6667;