linux網路程式設計基礎API(二)
阿新 • • 發佈:2019-01-06
編寫網路程式處除了要理解各種地址和必要的函式,還要檢測程式出錯。如果每次呼叫一個基本的socket函式都要判斷其結果是否正確,會給程式設計帶來麻煩。因此大多數都會定義包裹函式,對每一個基本socket函式進行封裝。下面是借鑑了《linux C程式設計一站式學習》中的程式碼進行整理:
#include <stdlib.h> #include <errno.h> #include <sys/socket.h> #include <unistd.h> #include <stdio.h> #include "wrap.h" void perr_exit(const char *s) { perror(s); exit(1); } int Socket(int family, int type, int protocol) { int n; if ( (n = socket(family, type, protocol)) < 0) perr_exit("socket error"); return n; } void Connect(int fd, const struct sockaddr *sa, socklen_t salen) { if (connect(fd, sa, salen) < 0) perr_exit("connect error"); } void Bind(int fd, const struct sockaddr *sa, socklen_t salen) { if (bind(fd, sa, salen) < 0) perr_exit("bind error"); } void Listen(int fd, int backlog) { if (listen(fd, backlog) < 0) perr_exit("listen error"); } int Accept(int fd, struct sockaddr *sa, socklen_t *salenptr){int n; again: if ( (n = accept(fd, sa, salenptr)) < 0) { if ((errno == ECONNABORTED) || (errno == EINTR)) goto again; else perr_exit("accept error"); } return n; } //有Readn就不用它了 ssize_t Read(int fd, void *ptr, size_t nbytes) { ssize_t n; again: if ( (n = read(fd, ptr, nbytes)) == -1) { if (errno == EINTR) goto again; else return -1; } return n; } //有Writen就不用它了 ssize_t Write(int fd, const void *ptr, size_t nbytes) { ssize_t n; again: if ( (n = write(fd, ptr, nbytes)) == -1) { if (errno == EINTR) goto again; else return -1; } return n; } void Close(int fd) { if (close(fd) == -1) perr_exit("close error"); } //讀n個位元組到prt中,返回實際讀到的位元組數,-1代表出錯 ssize_t Readn(int fd, void *vptr, size_t n) { size_t nleft; ssize_t nread; char *ptr; ptr = vptr; nleft = n;//剩下nleft未讀 while (nleft > 0) { if ( (nread = read(fd, ptr, nleft)) < 0) { if (errno == EINTR) nread = 0; else return -1;//出錯 } else if (nread == 0) break;//讀完 nleft -= nread; ptr += nread; } return n - nleft;//讀出的位元組數 } ssize_t Writen(int fd, const void *vptr, size_t n) { size_t nleft; ssize_t nwritten; const char *ptr; ptr = vptr; nleft = n; while (nleft > 0) { if ( (nwritten = write(fd, ptr, nleft)) <= 0) { if (nwritten < 0 && errno == EINTR) nwritten = 0; else return -1; } nleft -= nwritten; ptr += nwritten; } return n; }