Getting IP address in C

Discussion in 'C' started by hraja, May 7, 2010.

  1. hraja

    hraja New Member

    Joined:
    Apr 6, 2010
    Messages:
    5
    Likes Received:
    0
    Trophy Points:
    0
    Hi,

    I wish to get the system IP address in my C program. Unfortunately, when I tried the following code, I kept getting 127.0.1.1 and not the actual IP address of my system.

    struct sockaddr_in server_addr;
    struct hostent *host;
    char hostname[256];

    gethostname(hostname, sizeof(hostname));
    host = gethostbyname(hostname);
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(5000);
    server_addr.sin_addr = *((struct in_addr *)host->h_addr);
    printf("IP address: %s\n", inet_ntoa(server_addr.sin_addr));


    Thanks!
     
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,346
    Likes Received:
    382
    Trophy Points:
    83
    What is the string in your hostname?
     
  3. shaju1981

    shaju1981 New Member

    Joined:
    Jan 21, 2010
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    Perform WSAstartup before calling any socket function

    WORD wVersionRequested; WSADATA wsaData; int err;/* Use the MAKEWORD(lowbyte, highbyte) macro declared in Windef.h */ wVersionRequested = MAKEWORD(2, 2); err = WSAStartup(wVersionRequested, &wsaData);

    Now it may work .... :)
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice