Reputation: 115
I write a method, that creates a socket, connect it to the endpoint, and then returns its descriptor:
static int open_socket(const char* host, unsigned short port)
{
#ifdef USE_IPV4
struct hostent* _hostent;
struct sockaddr_in _sockaddr_in;
// Variables
size_t sockaddr_len;
int sock_family;
int sock_type;
int sock_protocol;
int sockfd;
_hostent = gethostbyname(host);
if (_hostent == (struct hostent*) 0)
{
// Not Found
}
_sockaddr_in.sin_family = AF_INET;
sock_family = AF_INET;
sock_type = SOCK_STREAM;
sock_protocol = IPPROTO_TCP;
sockaddr_len = sizeof(_sockaddr_in);
(void*) memmove(&_sockaddr_in, _hostent->h_addr, _hostent->h_length);
_sockaddr_in.sin_port = htons(port);
// Now create socket
sockfd = socket(sock_family, sock_type, sock_protocol);
if (sockfd < 0)
{
// "Internal Error"
}
if (connect(sockfd, (struct sockaddr*) &_sockaddr_in, sockaddr_len) < 0)
{
std::cerr << strerror(errno) << std::endl;
std::cerr << "Endpoint is unavailable" << std::endl;
return 0;
// "Unavailable"
}
return sockfd;
#endif
}
The error occures when i try to connect socket. strerror(errno) returns "Address family not supported by protocol". I cannot figure out why it happens, because in other samples AF_INET fine works with IPPROTO_TCP
Upvotes: 1
Views: 2172
Reputation: 37607
You need to store the address in sockaddr_in::sin_addr
instead. You are overwriting the entire struct (starting from the sin_family
) when you call memmove(&_sockaddr_in, ...)
.
Upvotes: 1