network.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /*
  2. * Network library.
  3. * Copyright (C) 1997 Kunihiro Ishiguro
  4. *
  5. * This file is part of GNU Zebra.
  6. *
  7. * GNU Zebra is free software; you can redistribute it and/or modify it
  8. * under the terms of the GNU General Public License as published by the
  9. * Free Software Foundation; either version 2, or (at your option) any
  10. * later version.
  11. *
  12. * GNU Zebra is distributed in the hope that it will be useful, but
  13. * WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with GNU Zebra; see the file COPYING. If not, write to the Free
  19. * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
  20. * 02111-1307, USA.
  21. */
  22. #include <zebra.h>
  23. #include "log.h"
  24. #include "network.h"
  25. /* Read nbytes from fd and store into ptr. */
  26. int
  27. readn (int fd, u_char *ptr, int nbytes)
  28. {
  29. int nleft;
  30. int nread;
  31. nleft = nbytes;
  32. while (nleft > 0)
  33. {
  34. nread = read (fd, ptr, nleft);
  35. if (nread < 0)
  36. return (nread);
  37. else
  38. if (nread == 0)
  39. break;
  40. nleft -= nread;
  41. ptr += nread;
  42. }
  43. return nbytes - nleft;
  44. }
  45. /* Write nbytes from ptr to fd. */
  46. int
  47. writen(int fd, const u_char *ptr, int nbytes)
  48. {
  49. int nleft;
  50. int nwritten;
  51. nleft = nbytes;
  52. while (nleft > 0)
  53. {
  54. nwritten = write(fd, ptr, nleft);
  55. if (nwritten <= 0)
  56. return (nwritten);
  57. nleft -= nwritten;
  58. ptr += nwritten;
  59. }
  60. return nbytes - nleft;
  61. }
  62. int
  63. set_nonblocking(int fd)
  64. {
  65. int flags;
  66. /* According to the Single UNIX Spec, the return value for F_GETFL should
  67. never be negative. */
  68. if ((flags = fcntl(fd, F_GETFL)) < 0)
  69. {
  70. zlog_warn("fcntl(F_GETFL) failed for fd %d: %s",
  71. fd, safe_strerror(errno));
  72. return -1;
  73. }
  74. if (fcntl(fd, F_SETFL, (flags | O_NONBLOCK)) < 0)
  75. {
  76. zlog_warn("fcntl failed setting fd %d non-blocking: %s",
  77. fd, safe_strerror(errno));
  78. return -1;
  79. }
  80. return 0;
  81. }