CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 10 of 10
  1. #1
    Join Date
    Jul 2006
    Posts
    4

    Extract substring from string

    i have a small console program that shows you, your ip and resolves from your ip your host name(reverse dns) and display then your ip and host name
    to the screen.
    an example output:
    Code:
    IP: 12.34.567.89
    Host Name: dslb-012-034-567-089.pools.myisp-ip.net
    now i want to convert the
    Code:
    dslb-012-034-567-089.pools.myisp-ip.net
    to
    Code:
    dslb.pools.myisp-ip.net
    or something similar.
    my goal is to remove the numbers and the "-" character from the host name string, because my ip is a dynamic ip and it changes every
    24hrs automatically. it should start to find the first "-" character and from there, until the first "." character or last
    number in the host name string and then cut out the found unneeded characters and then display the final host name string without the ip and
    the "-" character.
    i'm using msvc++ as compiler.

    how would i do that?

    any help and hints are more than welcome.
    Last edited by bigbang; September 17th, 2006 at 11:43 PM.

  2. #2
    Join Date
    Aug 2004
    Posts
    184

    Re: Extract substring from string

    There are many ways of doing this in C++....here are two examples, one using c style strings and another using std::string:

    Code:
    #include <cstdlib>
    #include <cstdio>
    #include <cstring>
    #include <string>
    using namespace std;
    int main( int argc, char** argv )
    {
    //----------------------------------------------------------------
    //-- using old c string routines
    //----------------------------------------------------------------
    char strResult[100] = { NULL };
    int strPosition = 0;
    char* testValue = "dslb-012-034-567-089.pools.myisp-ip.net";
     
    //-- get the position of the first dash and period
    char* strFromFirstDash = strchr( testValue, '-' );
    char* strFromFirstPeriod = strchr( testValue, '.' );
     
    //-- now find out how long the first string section is 
    strPosition = (strFromFirstDash -testValue);
     
    //-- build the new string
    strncpy( strResult, testValue, strPosition );
    strncat( strResult, strFromFirstPeriod, (99 - strPosition ));
     
    printf( "Using C string manipulation - %s\n", strResult );
     
    //----------------------------------------------------------------
    //-- using std::string
    //----------------------------------------------------------------
    string stringValue = "dslb-012-034-567-089.pools.myisp-ip.net";
     
    //-- get the position of the first dash and period 
    int dashPosition = stringValue.find_first_of( '-' );
    int periodPosition = stringValue.find_first_of( '.' );
     
    //-- build the new string removing the section we don't want 
    string stringNewValue = stringValue.substr(0, dashPosition );
    stringNewValue.append( stringValue.substr( periodPosition,
    					 stringValue.length() - periodPosition));
     
    printf( "Using std::string - %s\n", stringNewValue.c_str() );
     
    return 0;
    }
    NOTE: Error / Exception checking should be added.

    HTH

  3. #3
    Join Date
    Jul 2006
    Posts
    4

    Re: Extract substring from string

    thanks f1shrman, i could solve it with help from a good online friend, his hint was to use:
    Code:
    #include <stdio.h>
    
    void main()
    {
    char host[]="dslb-012-034-567-089.pools.myisp-ip.net";
    
    printf("\n %s ", host);
    strcpy(strchr(host,'-'),strchr(host,'.'));
    printf("\n %s",host);
    
    }
    output:
    Code:
     dslb-012-034-567-089.pools.myisp-ip.net 
     dslb.pools.myisp-ip.net
    and i modified it to:
    Code:
    	char* cShortHost = host->h_name;
    	strcpy(strchr(cShortHost, '-'), strchr(cShortHost, '.'));
    
    	printf("\nShortHost Name: %s", cShortHost);
    Last edited by bigbang; September 17th, 2006 at 11:42 PM.

  4. #4
    Join Date
    May 2005
    Location
    United States
    Posts
    263

    Re: Extract substring from string

    Quote Originally Posted by bigbang
    and i modified it to:
    char* cShortHost = host->h_name;
    strcpy(strchr(cShortHost, '-'), strchr(cShortHost, '.'));

    printf("\nShortHost Name: %s", cShortHost);
    Remember, the h_name member of "host" you do not own. Winsock determines when this string is deallocated. So you shouldn't mess with its pointer. You should make cShortHost a copy of host->h_name.

    -Greg Dolley

  5. #5
    Join Date
    Jul 2006
    Posts
    4

    Re: Extract substring from string

    Quote Originally Posted by greg_dolley
    Remember, the h_name member of "host" you do not own. Winsock determines when this string is deallocated. So you shouldn't mess with its pointer. You should make cShortHost a copy of host->h_name.

    -Greg Dolley
    interesting. you mean like that?
    Code:
        printf("IP: %s", cIP);
    	printf("\nHost Name: %s", host->h_name);
    
    	WritePrivateProfileString("IP Info", "IP",   cIP,          "c:\\IPtoHOST.ini");
    	WritePrivateProfileString("IP Info", "HOST", host->h_name, "c:\\IPtoHOST.ini");
    
    	strcpy(strchr(host->h_name, '-'), strchr(host->h_name, '.'));
    
    	printf("\nShortHost Name: %s", host->h_name);
    
        WSACleanup();
    
    	WritePrivateProfileString("IP Info", "SHORT HOST", host->h_name,   "c:\\IPtoHOST.ini");
    	MessageBox(NULL, "IP Info has been printed in C:\\IPtoHOST.ini", "IP Check", MB_OK);
    output will be like that:
    Code:
    IP: 12.34.567.89
    Host Name: dslb-012-034-567-089.pools.isp-ip.net
    ShortHost Name: dslb.pools.isp-ip.net
    p.s. can someone tell me where i can find here the codeformatbutton in the thread options?

    Code:
    test
    edit: found out i can use and type manualy [code][\code].
    Last edited by bigbang; September 17th, 2006 at 11:41 PM.

  6. #6
    Join Date
    May 2005
    Location
    United States
    Posts
    263

    Re: Extract substring from string

    No, you're still modifying host->h_name. You need to make a copy of h_name first, then do the manipulation, like this:

    Code:
    char *host_name = NULL;
    
    host_name = (char *)malloc(sizeof(char)*(strlen(host->h_name)+1));
    strcpy(host_name, host->h_name);
    -Greg Dolley

  7. #7
    Join Date
    May 2005
    Location
    United States
    Posts
    263

    Re: Extract substring from string

    Forgot something: now you just use the host_name variable to do all your manipulation.

    -Greg Dolley

  8. #8
    Join Date
    Jul 2006
    Posts
    4

    Re: Extract substring from string

    Quote Originally Posted by greg_dolley
    Forgot something: now you just use the host_name variable to do all your manipulation.

    -Greg Dolley
    Thank you alot greg_dolley.
    here's the win32 console program i was working on.

    //IPtoHOST.cpp
    Code:
    #include <windows.h>
    #include <wininet.h>
    #include <stdio.h>
    
    #pragma comment(lib, "Ws2_32.lib")
    #pragma comment(lib, "wininet.lib")
    
    #define AUTHOR "bigbang"
    
    char cIP[12];
    char* host_name = NULL;
    
    int initWinSock()
    {
    	WORD wVersionRequested;
    	WSADATA wsaData;
    	int err;
        
    	wVersionRequested = MAKEWORD(1, 1);
    	err = WSAStartup(wVersionRequested, &wsaData);
    
    	if (err != 0)
    	{
    		return -1;
    	}
    	return 0;
    } 
    
    void GetIP()
    {
    	HINTERNET hInet, hUrl;
    	DWORD     dwCode, dwLen;
    
    	if (NULL == (hInet = InternetOpen(TEXT("InetURL:/1.0"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0)))
    	printf("Unsuccessful InternetOpen\r\n");
    
    	else
    	{
    		printf("");
    
    		if (NULL != (hUrl = InternetOpenUrl(hInet, "http://iptohost.ip.funpic.de/ipcheck.php", NULL, 0, INTERNET_FLAG_RELOAD, 0)))
    		{
    			dwCode = 0;
    			dwLen  = sizeof(dwCode);
    
    			HttpQueryInfo(hUrl, HTTP_QUERY_STATUS_CODE, &dwCode, &dwLen, 0);
    			if ((dwCode == '002') || (dwCode == '203'))
    			{
    				if (InternetReadFile(hUrl, cIP, 256, &dwLen))
    				{
    					cIP[12] = '\0';
    				}
    			}
    			InternetCloseHandle(hUrl);
    		}
    		else
    		printf ("Apparently no valid url!\r\n");
    	}
    	InternetCloseHandle(hInet);
    }
    
    int main()
    {
    	system("color 9F");
    	printf("+---------------------+\n");
    	printf("+ IPtoHOST by %s +\n", AUTHOR);
    	printf("+---------------------+\n\n");
    
    	GetIP();
    
        struct hostent *host;
        struct in_addr addr;
    
        if (initWinSock())
    	{
            printf("Error! Can't initialize winsock\n");
            return 1;
        }
    
        addr.s_addr = inet_addr(cIP);
        if (addr.s_addr == INADDR_NONE)
    	{
            host = gethostbyname(cIP);
        }
        else
    	{
            host = gethostbyaddr((const char *)&addr, sizeof(struct in_addr), AF_INET);
        }
    
        if (host == NULL)
    	{
            printf("Cannot resolve address %s. Error code: %d\n", GetIP, WSAGetLastError());
            return 1;
        }
    
        printf("IP: %s", cIP);
    	printf("\nHost Name: %s", host->h_name);
    
    	WritePrivateProfileString("IP Info", "IP",   cIP,          "c:\\IPtoHOST.ini");
    	WritePrivateProfileString("IP Info", "HOST", host->h_name, "c:\\IPtoHOST.ini");
    
    	host_name = (char *)malloc(sizeof(char)*(strlen(host->h_name)+1));
    	strcpy(host_name, host->h_name);
    
    	strcpy(strchr(host_name, '-'), strchr(host_name, '.'));
    
    	printf("\nShortHost Name: %s", host_name);
    
    
        WSACleanup();
    
    	WritePrivateProfileString("IP Info", "SHORT HOST", host_name,   "c:\\IPtoHOST.ini");
    	MessageBox(NULL, "IP Info has been printed in C:\\IPtoHOST.ini", "IP Check", MB_OK);
    
    	free(host_name);
    
        return 0;
    }
    //ipcheck.php
    Code:
    <?
    $ipadresse ="$REMOTE_ADDR"; 
    echo "$ipadresse";
    ?>
    i think the hname pointer problem is fixed now?

    output is:
    Code:
    IP: 12.34.567.89
    Host Name: dslb-012-034-567-089.pools.isp-ip.net
    ShortHost Name: dslb.pools.isp-ip.net
    Last edited by bigbang; September 18th, 2006 at 01:21 PM.

  9. #9
    Join Date
    May 2005
    Location
    United States
    Posts
    263

    Re: Extract substring from string

    Quote Originally Posted by bigbang
    i think the hname pointer problem is fixed now?
    There ya go! Much better.

    One more thing: remember to free the "host_name" string before exiting. Just, "free(host_name);" will do the trick.

    Greg Dolley

  10. #10
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Extract substring from string

    Quote Originally Posted by bigbang
    Thank you alot greg_dolley.
    here's the win32 console program i was working on.
    Your code has a memory leak. You called malloc() without calling free() to release the memory.

    Regards,

    Paul McKenzie

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured