编辑
我已经对下面看到的进行了更改,这就是我所拥有的
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/un.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <string>
#include <vector>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <errno.h>
using namespace std;
string buffer;
vector<string> ex;
int s;
void recvline ( int s, string* buf ) {
char in, t;
while ( 1 ) {
recv ( s, &in, 1, 0 );
*buf += in;
if ( in == 10 ) {
t = 1; }
if ( t && in == 13 ) {
break; }
}
}
void push ( int s, string msg ) {
string o = msg + "\r\n";
cout << "SENT:", o;
send ( s, o.c_str(), o.size(), 0 );
}
int main ( int argc, char *argv[] ) {
if ( argc < 3 ) {
cout << "Insufficient Arguments" << endl;
exit ( 7 ); }
s = socket ( AF_INET, SOCK_STREAM, IPPROTO_TCP );
if ( s < 0 )
exit ( 1 );
struct hostent h = *gethostbyname ( argv[1] );
struct sockaddr_in c;
c.sin_family = AF_INET;
c.sin_port = htons(atoi(argv[2]));
c.sin_addr.s_addr = inet_addr ( h.h_addr_list[0] );
if ( connect ( s, (struct sockaddr*)&c, sizeof c ) != 0 ) {
cout << "Unable to connect to network" << endl;
cout << strerror(errno) << endl;
exit ( 2 );
}
push ( s, "USER LOLwat Lw lol.wat :LOLwat" );
push ( s, "NICK LOLwat" );
while ( true ) {
recvline ( s, &buffer );
cout << buffer;
if ( buffer.substr(0,4).c_str() == "PING" )
push ( s, "PONG " + buffer.substr(6,-2) );
}
}
这是结果:
[dbdii407@xpcd Desktop]$ g++ ?.cpp -o 4096 -
[dbdii407@xpcd Desktop]$ ./4096 irc.scrapirc.com 6667 - Unable to connect to network - Network is unreachable
最佳答案
我认为问题在于这一行:
c.sin_port = htons(*argv[2]);
没有按照您的想法去做。 argv[2]
是一个字符串,*argv[2]
是字符串的第一个字符。因此,如果您将“4567”作为第二个命令行参数传递,则 *argv[2]
将为“4”,其 ASCII 值为 52。这意味着您将尝试连接到端口52,而不是您期望的“4567”。
将行更改为:
c.sin_port = htons(atoi(argv[2]));
atoi 函数接受一个字符串并将其转换为整数。所以“4567”会变成 4567。
此外,一般来说,当这样的函数调用失败时,您应该检查 errno
的值(它通常会在 the documentation 中告诉您是否设置了 errno 以及可以设置的可能值到)。这应该有助于在未来为您提供一些线索。
编辑
正如其他人指出的那样,请务必注意您的牙套。如果您只是总是在if
、while
等周围使用大括号,通常会更容易。也就是说,这个:
if ( connect ( s, (struct sockaddr*)&c, sizeof c ) != 0 )
cout << "Unable to connect to network" << endl;
exit ( 2 );
与此完全不同:
if ( connect ( s, (struct sockaddr*)&c, sizeof c ) != 0 ) {
cout << "Unable to connect to network" << endl;
exit ( 2 );
}
关于C++ 套接字连接错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3098926/