Linux C socket 封装
/************************************************************************** * Linux C socket 封装 * 声明: * 同样的代码当然没必要敲很多遍了,一遍就够了,封起来,什么时候要用, * 什么时候就来这里拿。 * * 2015-7-4 晴 深圳 南山平山村 曾剑锋 *************************************************************************/ \\\\\\\\-*- 目录 -*-//////// | 一、cat zengjf_socket.h | 二、cat zengjf_socket.c \\\\\\\\\\\\\\////////////// 一、cat zengjf_socket.h #ifndef __ZENGJF_SOCKET_H__ #define __ZENGJF_SOCKET_H__ #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 <unistd.h> #define handle_error(msg) { perror(msg); exit(EXIT_FAILURE); } /** * 客户端socket * 参数说明: * 1.ip:服务器ip地址,点分十进制的ip字符串 * 2.port:服务器端口号,字串的形式 * 3.srvaddr:连接到服务器端的sockaddr_in */ int socketClient(char* ip, char* port, struct sockaddr_in* srvaddr); /** * 服务器端socket * 参数说明: * 1.port:监听端口号,是字串的形式 * 2.srvaddr:服务器的sockaddr_in * * * 服务器端socket默认能够同时监听30个连接 */ int socketServer(char* port, struct sockaddr_in* srvaddr); #endif // __ZENGJF_SOCKET_H__ 二、cat zengjf_socket.c #include "zengjf_socket.h" int socketClient(char* ip, char* port, struct sockaddr_in* srvaddr){ int sfd; // create a socket if ((sfd = socket(AF_INET, SOCK_STREAM, 0)) == -1){ handle_error("can not create socketClient."); } // set the server socket address srvaddr->sin_family = AF_INET; srvaddr->sin_port = htons(atoi(port)); inet_aton(ip, &(srvaddr->sin_addr)); // connect if (connect(sfd, (struct sockaddr *)srvaddr, sizeof(struct sockaddr)) == -1){ handle_error("can not connect to server."); } return sfd; } int socketServer(char* port, struct sockaddr_in* srvaddr){ int srv_fd; //the default listen count int listenCount = 30; // create a socket if ((srv_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1){ handle_error("can not create socketServer."); } //reuse the socket address int sockopt = 1; setsockopt(srv_fd, SOL_SOCKET, SO_REUSEADDR, &sockopt, sizeof(sockopt)); // set the socket address srvaddr->sin_family = AF_INET; srvaddr->sin_port = htons(atoi(port)); srvaddr->sin_addr.s_addr = htonl(INADDR_ANY); // bind the socket with the address if (bind(srv_fd, (struct sockaddr *)srvaddr, sizeof(struct sockaddr)) == -1){ handle_error("can not bind the address."); } // listening // default was 30 if (listen(srv_fd, listenCount) == -1){ handle_error("can not listening to the port."); } return srv_fd; }