I have this code:
#include <stdio.h>
#include <string.h>
int main()
{
char buf[255];
char buf2[255];
char myhost[255] = "subdomain.domain.com";
char *pch;
int token_counter = 0;
memset(buf, 0, 255);
memset(buf2, 0, 255);
pch = strtok(myhost, ".");
while (pch != NULL)
{
pch = strtok(NULL, ".");
if (pch == NULL)
{
memset(buf, 0, 255);
strncpy(buf, buf2, strlen(buf2) - 1);
break;
}
token_counter++;
strcat(buf2, pch);
strcat(buf2, ".");
}
printf("Domain: %s\n", buf);
return 0;
}
this is working fine if myhost is defined as subdomain.domain.com but if it’s domain.com it shows “com” as final result.
How can I make it detect correctly if it’s a subdomain or a domain? Maybe if I include a list of known tlds?
strtokis overkill andstrcatis wasteful. If you just want to print everything past the nth., usestrchror just examine the string to find the nth.. If so desired, count from the end of the string.Let me explain why
strcatis a waste of time here. Consider:If you want to print “baz.qux.net”, you do not need to copy that string into a new buffer since you already have a pointer to the first character of the desired string. Use what you have. All you need to do is find a pointer to the desired
.in the string, and then doprintf( "%s\n", dot + 1 )orputs( dot + 1 ). (putsis better here, but you are probably more familiar withprintf)