Get IP of local (host) computer

Often when programming simple TCP/IP server (for monitoring of services and other non-GUI-based applications, etc.) we need to know IP of the host computer so that clients can connect to it; to retrieve this IP from within the server-side program, use the following snippet:

WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD(2, 0);

if (WSAStartup(wVersionRequested, &wsaData ) != 0)
{
    printf("WSAStartup() failed!n");
    return 0;
}

// Get the local host information
hostent* localHost = gethostbyname("");
char* localIP = inet_ntoa(*(struct in_addr *)*localHost->h_addr_list);

printf("Local host IP is: %sn", localIP);

WSACleanup();

Includes
WinSock2.h, Ws2tcpip.h

Link libraries
ws2_32.lib

Once I get some time on my hands, I’ll clean up and post the code of my WinSock-based TCP/IP library for simple development of both server and client side.

4 responses to “Get IP of local (host) computer

  1. Right here is the right site for everyone who hopes to
    find out about this topic. You realize so much its almost hard
    to argue with you (not that I really will need to…HaHa). You definitely put a brand new spin on a topic
    which has been written about for years. Excellent stuff, just wonderful!

  2. Excellent website you have here but I was wanting to know if you
    knew of any community forums that cover the same topics discussed here?

    I’d really love to be a part of online community where
    I can get feedback from other experienced people that share the same interest.
    If you have any suggestions, please let me know. Cheers!

  3. Hello to every body, it’s my first go to see of this webpage; this web site contains awesome and truly good material in favor of visitors.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s