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?