我正在尝试创建一个监视 IRC 服务器的程序,即使连接的基础知识也遇到了麻烦。我正在我的学校开发一个 linux 集群。
我根本不知道我做错了什么。这是我的代码,几乎一字不差地从 C 语言中的 TCP IP 套接字第 2 章复制而来。
int main(int argc, char** argv)
{
char *servName = "irc.freenode.net";
in_port_t servPort = 6667;
//Start populating server information into a sockaddr
struct sockaddr_in servAddr;
memset(&servAddr, 0, sizeof(servAddr));
//To get the IP address of irc.freenode.net
//Using gethostbyname
char servIP[16];
struct hostent *hent;
hent = gethostbyname(servName);
inet_ntop(AF_INET, (void *)hent->h_addr_list[0],servIP,16);
//Convert the IP address's endianness
int rtnVal = inet_pton(AF_INET, servIP, &servAddr.sin_addr.s_addr);
if(rtnVal <= 0)
dieMsg("inet fail",rtnVal);
servAddr.sin_port = htons(servPort);
servAddr.sin_family = AF_INET;
printf("%s\n",servIP);
//End server information
//Open a socket to use
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(sock<0)
dieMsg("sock fail",sock);
//Connect using the sock, and the populated sockaddr struct.
if(connect(sock,(struct sockaddr*) &servAddr, sizeof(servAddr))<0);
{
dieMsg("con fail",-1);
}
return 0;
}
dieMsg
是一个函数,它接受一个字符串和一个 int,打印它们,然后退出。
这段代码的输出是
89.16.176.16
con fail -1
或者,我也使用了addrinfo
结构,但无济于事:
int main(int argc, char** argv)
{
char *servHostc = "irc.freenode.net";
char *servPortc = "6667";
struct addrinfo addrCriteria;
memset(&addrCriteria, 0, sizeof(addrCriteria));
addrCriteria.ai_family = AF_INET;
addrCriteria.ai_socktype = SOCK_STREAM;
addrCriteria.ai_protocol = IPPROTO_TCP;
struct addrinfo *servAddr;
int rtnVal = getaddrinfo(servHostc,servPortc, &addrCriteria, &servAddr);
if(rtnVal != 0)
dieMsg("getaddrinfo() connect fail", rtnVal);
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(connect(sock, (struct sockaddr*) &servAddr, sizeof(servAddr) < 0))
{
free(servAddr);
dieMsg("Connect failed",-1);
}
return 0;
}
Telnet 对这两个地址都有效,所以这不是我的互联网连接。
$ telnet irc.freenode.net 6667
Trying 128.237.157.136...
Connected to irc.freenode.net (128.237.157.136).
Escape character is '^]'.
:hubbard.freenode.net NOTICE * :*** Looking up your hostname...
:hubbard.freenode.net NOTICE * :*** Checking Ident
:hubbard.freenode.net NOTICE * :*** Found your hostname
^]
telnet> Connection closed.
$ telnet 89.16.176.16 6667
Trying 89.16.176.16...
Connected to wolfe.freenode.net (89.16.176.16).
Escape character is '^]'.
:wolfe.freenode.net NOTICE * :*** Looking up your hostname...
:wolfe.freenode.net NOTICE * :*** Checking Ident
:wolfe.freenode.net NOTICE * :*** Found your hostname
^]
telnet> Connection closed.
我通常讨厌问问题,所以这是我最后的手段。如果有人可以请阐明我的困境,我将不胜感激。