In all the example including Beej's Guide, the IP address is provided in dot notation and then it's fed to ::getaddrinfo()
. This post doesn't answer my question.
After which the addrinfo
struct is used for socket related functions (e.g. connect()
, bind()
, listen()
). For example:
struct addrinfo hints, *res;
// ... create socket etc.
connect(sockfd, res->ai_addr, res->ai_addrlen);
Example
The variable ai_addr
is of type sockaddr
which can be safely typecasted to sockaddr_storage
, sockaddr_in
and sockaddr_in6
.
Question:
If I typecast sockaddr
to sockaddr_in
(or sockaddr_in6
)
sockaddr_in& ipv4 = (sockaddr_in&)(sockaddr_variable);
and feed below info:
- ipv4.sin_family = AF_INET
- ipv4.sin_addr = [IP Address in net byte order]
- ipv4.sin_port = [Port number in net byte order]
Can I call the connect()
method directly using above info?
connect(sockfd, &ipv4, sizeof(ipv4));
With my program it doesn't appear to work. Am I missing something, or is there a better way?
The motivation behind is that, if we have the information of IPAddress, Port etc. in socket readable format then why to go through the cycle of getaddrinfo()