Thread: Need help with retrieving and adding WAN IP to file

  1. #1
    Registered User
    Join Date
    May 2007
    Posts
    1

    Unhappy Need help with retrieving and adding WAN IP to file

    Hi all, I need some help here. I'm just learning.
    This is what i have so far.

    I am able to retrieve my wan ip address and use printf to display the full WANIP. But if I try to save it to a file all I get is: WAN IP: 2

    I have linked the wininet lib, also

    Any help here is greatly appreciated.


    Code:
    #include <wininet.h>
    #include <stdio.h> 
    
    #define AUTHOR "Oh"
    
    CHAR buffer[100];
    int i=75;
    
    int main(int argc, char *argv[])
    {
    
    HINTERNET hINet, hFile;
    CHAR buffer[100];
    
    
    hINet = InternetOpen(AUTHOR, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0 );
    
    if ( !hINet )
    {
    
    printf("No Internet Connection");
    
    }
    
    hFile = InternetOpenUrl( hINet,"http://checkip.dyndns.org/" , NULL, 0, 0, 0 );
    
    
    if ( hFile )
    {
    
    DWORD dwRead;
    InternetReadFile( hFile, buffer, 100, &dwRead );
    } 
    InternetCloseHandle( hFile );
    
    InternetCloseHandle( hINet );
    printf("WAN IP:");
    
    while ((buffer[i] != 0x3C) && (i < sizeof(buffer)))
    {
    printf("%c",buffer[i]);
    i++;
    }
    getchar();
    return 0;
    
    while ((buffer[i] != 0x3C) && (i < sizeof(buffer)))
    {
    FILE *pFile;
    
      pFile = fopen ("c:\\test.txt","w");
      fprintf (pFile, "WAN IP: ");
      fprintf (pFile,"%c", buffer[i]);
      ++i;
    }
    return 0;
    
    }

  2. #2
    Registered User
    Join Date
    May 2007
    Posts
    88
    Few things:
    #1. Indent your code.
    #2. This is a C program, also it's Windows-specific.

    Nitpicking aside, the problem most likely has something to do with the fact that your loop variable i is not reset to 0 ( or whatever it was initially) after the first loop. There are most likely much better ways of writing this program, but I'm not that great with C, so maybe someone else can help.
    Last edited by UMR_Student; 05-15-2007 at 04:30 PM.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Another problem is you're opening (and not closing) the file INSIDE the while loop.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed