Programming Tips - C/C++: Extract host name from a URL without using a libary

Date: 2021feb6 Date: 2026sep25 Language: C/C++ Libary: none Keywords: server, computer name Q. C/C++: Extract host name from a URL without using a libary A.
#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'; }
Example Use:
int main() { char szHost[300]; ExtractHostFromUrl("https://google.com", szHost, sizeof(szHost)); printf("host1=%s\n", szHost); ExtractHostFromUrl("rstp://www.example.com", szHost, sizeof(szHost)); printf("host2=%s\n", szHost); }
Output:
host1=google.com host2=www.example.com