parseurl.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2022, Daniel Stenberg, <daniel@haxx.se>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at https://curl.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. * SPDX-License-Identifier: curl
  22. *
  23. ***************************************************************************/
  24. /* <DESC>
  25. * Basic URL API use.
  26. * </DESC>
  27. */
  28. #include <stdio.h>
  29. #include <curl/curl.h>
  30. #if !CURL_AT_LEAST_VERSION(7, 62, 0)
  31. #error "this example requires curl 7.62.0 or later"
  32. #endif
  33. int main(void)
  34. {
  35. CURLU *h;
  36. CURLUcode uc;
  37. char *host;
  38. char *path;
  39. h = curl_url(); /* get a handle to work with */
  40. if(!h)
  41. return 1;
  42. /* parse a full URL */
  43. uc = curl_url_set(h, CURLUPART_URL, "http://example.com/path/index.html", 0);
  44. if(uc)
  45. goto fail;
  46. /* extract host name from the parsed URL */
  47. uc = curl_url_get(h, CURLUPART_HOST, &host, 0);
  48. if(!uc) {
  49. printf("Host name: %s\n", host);
  50. curl_free(host);
  51. }
  52. /* extract the path from the parsed URL */
  53. uc = curl_url_get(h, CURLUPART_PATH, &path, 0);
  54. if(!uc) {
  55. printf("Path: %s\n", path);
  56. curl_free(path);
  57. }
  58. /* redirect with a relative URL */
  59. uc = curl_url_set(h, CURLUPART_URL, "../another/second.html", 0);
  60. if(uc)
  61. goto fail;
  62. /* extract the new, updated path */
  63. uc = curl_url_get(h, CURLUPART_PATH, &path, 0);
  64. if(!uc) {
  65. printf("Path: %s\n", path);
  66. curl_free(path);
  67. }
  68. fail:
  69. curl_url_cleanup(h); /* free url handle */
  70. return 0;
  71. }