0

I am writing a function to connect client-server. And i cannot use gethostbyname. This function is simple to use. Now i don't know how to use getaddrinfo. How can i change gethostbyname into getaddrinfo. Thank you so much!

void ConnectSocket()
{
    WSADATA wsaData;
    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
    {
        return;
    }

skt = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

struct hostent* host;

host = gethostbyname("127.0.0.1");

SOCKADDR_IN sockAddr;

sockAddr.sin_port = htons(45444);
sockAddr.sin_family = AF_INET;
sockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);

if (connect(skt, (SOCKADDR*)&sockAddr, sizeof(sockAddr)) != 0) {
    return;
}
}
  • For the loopback address, why not use `INADDR_LOOPBACK` instead? As in `sockAddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK)` – Some programmer dude Aug 31 '20 at 10:10
  • 1
    As for how to use `getaddrinfo`, there must be several thousands of tutorials and examples, all over the Internet. Can you please be more specific about the problems you have? And please take some time to read (or refresh) [the help pages](http://stackoverflow.com/help), take the SO [tour], read [ask], as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). – Some programmer dude Aug 31 '20 at 10:11
  • On my Fedora Linux system, "man getaddrinfo" actually provides complete, working code samples ;) – Kevin Boone Aug 31 '20 at 17:41
  • On line is the linux web page: `https://man7.org/linux/man-pages/man3/getaddrinfo.3.html` which includes everything you might want to know about that function, including an example written in c – user3629249 Sep 01 '20 at 15:23

0 Answers0