C ++套接字连接错误

时间:2010-06-23 04:24:17

标签: c++ sockets irc

修改

我已经对下面看到的内容进行了更改,这就是我的内容

#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

2 个答案:

答案 0 :(得分:3)

我认为问题在于这一行:

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以及可能的值是否可以调成)。这应该有助于在将来为您提供一些线索。

修改
正如其他人所说,确保你注意你的牙套。如果您只是始终使用ifwhile等大括号,通常会更容易。就是这样:

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 );
}

答案 1 :(得分:2)

我决定完全重做我的回答,部分原因是gethostbyname联机帮助页中的以下评论:

  

gethostbyname *()和   gethostbyaddr *()函数是   过时。应用应该使用   getaddrinfo(3)和getnameinfo(3)   代替。

以下是基于使用getaddrinfo的返工程序(使用bcpp进行了清理)。我强烈建议总是使用以下选项进行编译:

 g++ -Wall -Wextra irc.cpp -o irc

这会在您的代码中显示以下错误:

irc.cpp: In function ‘void push(int, std::string)’:
irc.cpp:40: warning: right-hand operand of comma has no effect
irc.cpp: In function ‘int main(int, char**)’:
irc.cpp:87: warning: comparison with string literal results in unspecified behaviour

我继续修复错误。另外,尽量尝试消除全局变量。

#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;

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 );
    }

    int s, sfd;
    struct addrinfo *result, *rp;

    s = getaddrinfo(argv[1], argv[2], NULL, &result);
    if (s != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
        exit(EXIT_FAILURE);
    }

    for (rp = result; rp != NULL; rp = rp->ai_next) {
        sfd = socket(rp->ai_family, rp->ai_socktype,
                    rp->ai_protocol);
        if (sfd == -1)
            continue;

        if (connect(sfd, rp->ai_addr, rp->ai_addrlen) != -1)
            break;                  /* Success */

        close(sfd);
    }

    if (rp == NULL) {               /* No address succeeded */
        fprintf(stderr, "Could not connect\n");
        exit(EXIT_FAILURE);
    }

    freeaddrinfo(result);           /* No longer needed */

    push ( sfd, "USER LOLwat Lw lol.wat :LOLwat" );
    push ( sfd, "NICK LOLwat" );
    while ( true )
    {
        recvline ( sfd, &buffer );
        cout << buffer;
        if ( buffer.substr(0,4) == "PING" )
            push ( sfd, "PONG " + buffer.substr(6,-2) );
    }
}