1

So I was writing a c++ class to make unix sockets in c a bit easier. However, every time I run it it fails to connect. The value of the port changes midway through the program. Here is the header file with the class:

#ifndef __Sockets__CHSocket__
#define __Sockets__CHSocket__
class Sock {
    int port;
    char host[16];
    int sock,maxLen;
    int bytes;
    long nHostAddress;
    struct hostent* pHostInfo;
    struct sockaddr_in dest;

public:
    Sock(int dom, int type);
    int connct(const char *host, int port);
    int bnd(const char *addr, int port);
    int lstn(int port);
    int snd(const char *toSend);
    int sndto(const char *msg, const char *dst);
    char* recv(int length);
    int accpt(int s, struct sockaddr *addr, socklen_t *addrlen);
    int clse();
};  
#endif /* defined(__Sockets__CHSocket__) */

Here is CHSocket.cpp (shortened to what is actually run):

// Constructor definition
Sock::Sock(int dom, int type)
{
    bzero(&dest, sizeof(dest));
    if ((sock=socket(dom, type, 0)<0)) {
        cerr << "[!] Failed to create socket!;";
    }
    dest.sin_family=dom;
    memset(&dest, 0, sizeof(dest));
}

// Connect definition
int Sock::connct(const char *host, int port)
{
    char theHost[sizeof(host)];
    strcpy(theHost, host);
    pHostInfo=gethostbyname(theHost);
    memcpy(&nHostAddress,pHostInfo->h_addr,pHostInfo->h_length);

    dest.sin_addr.s_addr=nHostAddress;
    dest.sin_port = htons(port);
    if (connect(sock, (struct sockaddr *)&dest, sizeof(dest)) < 0)
    {
        cerr << "[!] Failed to connect socket!";
        return -1;
    }
    else
    {
        return 0;
    }
    return 0;
}

Here is main.cpp:

int main()
{
    Sock test = Sock(AF_INET, SOCK_STREAM);
    test.connct("127.0.0.1", 3000);
    test.clse();
}

I am using xcode 5 on osx 10.8. When I ran the program it told me that it could not connect. I put in some breakpoints at the very beginning of the connect function and at the line that defines pHostInfo. At the first break point, value of port is 3000, at the second, it is 49. Is this related to the connect issue?

UPDATE:

The program runs now but it gives me the following output:

[!] Failed to connect socket!Program ended with exit code: 0

This is what it does when it fails to connect the socket. I have netcat listening on port 3000 and I successfully connected from another window. Any ideas what the issue might be?

4

2 回答 2

3
char theHost[sizeof(host)];

给你一个空间为sizeof(char*). 您实际上需要strlen(host)+1字节,因此可能会在后续的strcpy. 改变这一点需要支持 VLA(不作为标准存在)或不必要的动态分配。

theHost删除,在它的位置使用会更容易host

于 2013-10-11T23:32:42.557 回答
3
char theHost[sizeof(host)];

该行分配了足够的字节来存储 的大小host,这是一个指向 char 的指针,可能是 8。然后它会覆盖端口号,因为您没有在堆栈上分配足够的内存。您可能需要以下内容:

char *theHost = new char[strlen(host)+1]

然后在构造函数返回之前释放该内存:

delete [] theHost;

或者,更简单更好的是,您可以host直接在调用中使用该参数gethostbyname()

编辑:(按照建议添加了释放)

于 2013-10-11T23:33:14.443 回答