摘自:https://segmentfault.com/a/1190000012086550
usock
即是对网络套接字连接的简单封装。
类型标志:
#define USOCK_TCP 0 #define USOCK_UDP 1 #define USOCK_SERVER 0x0100 #define USOCK_NOCLOEXEC 0x0200 #define USOCK_NONBLOCK 0x0400 #define USOCK_NUMERIC 0x0800 #define USOCK_IPV6ONLY 0x2000 #define USOCK_IPV4ONLY 0x4000 #define USOCK_UNIX 0x8000
接口函数:
/** * 创建一个sock * * @param type - 类型标志 * @param host - 作为server表示绑定本地地址;作为client表示需连接的地址 * @param service - 端口 * @return - sock fd > 0; 错误 < 0 */ int usock(int type, const char *host, const char *service);
客户端代码:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include "libubox/usock.h" int main(int argc, char** argv) { struct sockaddr cli_addr; socklen_t len = sizeof(struct sockaddr); int type = USOCK_TCP | USOCK_NOCLOEXEC | USOCK_IPV4ONLY; const char *host = "127.0.0.1"; const char *service = "8000"; char recv_buf[1024] = {0}; // printf("port: %s ", usock_port(8888)); int c_fd = usock(type, host, service); if(c_fd < 0) { perror("usock"); return -1; } send(c_fd, "helloworld", 10, 0); sleep(2); close(c_fd); return 0; }
服务端代码:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include "libubox/usock.h" int main(int argc, char** argv) { struct sockaddr_in cli_addr; socklen_t len = sizeof(struct sockaddr); int type = USOCK_TCP | USOCK_SERVER | USOCK_NOCLOEXEC | USOCK_IPV4ONLY; const char *host = "127.0.0.1"; const char *service = "8000"; char recv_buf[1024] = {0}; int connect_fd, u_fd; u_fd = usock(type, host, service); if(u_fd < 0) { perror("usock"); return -1; } while (1) { connect_fd = accept(u_fd, (struct sockaddr *)(&cli_addr), &len); if (connect_fd < 0) { perror("accept"); return -1; } printf("client_addr: %s ", inet_ntoa(cli_addr.sin_addr)); recv(connect_fd, recv_buf, 1024, 0); printf("recv %s ", recv_buf); close(connect_fd); } return 0; }