inetcli.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /* Byte Stream Socket Example
  2. Copyright (C) 1991-2019 Free Software Foundation, Inc.
  3. This program is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU General Public License
  5. as published by the Free Software Foundation; either version 2
  6. of the License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program; if not, see <http://www.gnu.org/licenses/>.
  13. */
  14. #include <stdio.h>
  15. #include <errno.h>
  16. #include <stdlib.h>
  17. #include <unistd.h>
  18. #include <sys/types.h>
  19. #include <sys/socket.h>
  20. #include <netinet/in.h>
  21. #include <netdb.h>
  22. #define PORT 5555
  23. #define MESSAGE "Yow!!! Are we having fun yet?!?"
  24. #define SERVERHOST "www.gnu.org"
  25. void
  26. write_to_server (int filedes)
  27. {
  28. int nbytes;
  29. nbytes = write (filedes, MESSAGE, strlen (MESSAGE) + 1);
  30. if (nbytes < 0)
  31. {
  32. perror ("write");
  33. exit (EXIT_FAILURE);
  34. }
  35. }
  36. int
  37. main (void)
  38. {
  39. extern void init_sockaddr (struct sockaddr_in *name,
  40. const char *hostname,
  41. uint16_t port);
  42. int sock;
  43. struct sockaddr_in servername;
  44. /* Create the socket. */
  45. sock = socket (PF_INET, SOCK_STREAM, 0);
  46. if (sock < 0)
  47. {
  48. perror ("socket (client)");
  49. exit (EXIT_FAILURE);
  50. }
  51. /* Connect to the server. */
  52. init_sockaddr (&servername, SERVERHOST, PORT);
  53. if (0 > connect (sock,
  54. (struct sockaddr *) &servername,
  55. sizeof (servername)))
  56. {
  57. perror ("connect (client)");
  58. exit (EXIT_FAILURE);
  59. }
  60. /* Send data to the server. */
  61. write_to_server (sock);
  62. close (sock);
  63. exit (EXIT_SUCCESS);
  64. }