Date: 2021feb6
Language: C/C++
Libary: none
Keywords: server, computer name
Q. C/C++: extract host name from a URL without using a libary
#include <stdio.h>
#include <string.h>
// "http://example.com/path" or "http://example.com" or "https://example.com:90"
void ExtractHostFromUrl(const char *szUrl, char *szHost, const size_t size) {
const char *p;
char *q = szHost;
int n = 0;
szHost[0] = '\0';
if ((p = strstr(szUrl, "//")) == NULL) return;
for (p += 2; *p; p++ ){
if (n >= (int)size) break;
if (*p == ':' || *p == '/') break;
*q++ = *p;
n++;
}
*q = '\0';
}
void ExampleUse() {
char szHost[300];
ExtractHostFromUrl("https://google.com", szHost, sizeof(szHost));
printf("host=%s\n", szHost);
}