NO

Author Topic: IP address  (Read 4607 times)

post from old forum

  • Guest
IP address
« on: September 13, 2004, 09:15:22 PM »
How can I learn my own ip address? By gethostname? Can anybody send me an example code?

bera

post from old forum

  • Guest
IP address
« Reply #1 on: September 13, 2004, 09:20:39 PM »
If all you need is to be able to connect to yourself, you should use the loopback address (127.0.0.1) to do it. If all you want is to open a socket for listening, you'd use INADDR_ANY or INADDR_LOOPBACK rather than needing the address.
If you really need the ip address, here's an example:

Code: [Select]

#include <stdio.h>
#define WIN32_LEAN_AND_MEAN
#include <winsock.h>

int main(void){
    char hname[512];
    WSADATA wsaData;
    struct hostent *he;
    int i = 0;
    if (WSAStartup(MAKEWORD(1,1),&wsaData) != 0) {
        printf("Error on WSAStartup()\n");
        return -1;
    }
    if (gethostname(hname,sizeof(hname)) == SOCKET_ERROR) {
        printf("Error on gethostname()\n");
        return -1;
    }
    he = gethostbyname(hname);
    if (he == 0) {
        printf("Error on gethostbyname()\n");
        return -1;
    }
    while (he->h_addr_list[i] != 0) {
        struct in_addr ia;
        memcpy(&ia,he->h_addr_list[i],sizeof(struct in_addr));
        printf("Local address found: %s\n",inet_ntoa(ia));
        i++;
    }
    WSACleanup();
    return 0;
}


Ako[/code]