#include #include #include #include #include #include #include #include #include #include #ifndef AF_SMC #define AF_SMC 43 #endif #define NET_PROTOCAL AF_INET #define SERV_IP "0.0.0.0" #define SERV_PORT 10012 int net_serv(int buf_size, int port) { int sndbuf_size, rcvbuf_size; struct sockaddr_in s_addr; struct sockaddr_in c_addr; char msg[128] = "Request"; int l_sock, s_sock; int optlen = 4; if (!port) port = SERV_PORT; l_sock = socket(NET_PROTOCAL, SOCK_STREAM, 0); if (buf_size) { sndbuf_size = rcvbuf_size = buf_size; /* set sndbuf and rcvbuf */ if (setsockopt(l_sock, SOL_SOCKET, SO_SNDBUF, &sndbuf_size, sizeof(int))) { printf("set sndbuf failed\n"); return 0; } if (setsockopt(l_sock, SOL_SOCKET, SO_RCVBUF, &rcvbuf_size, sizeof(int))) { printf("set rcvbuf failed\n", rcvbuf_size); return 0; } } memset(&s_addr, 0, sizeof(struct sockaddr_in)); s_addr.sin_family = NET_PROTOCAL; s_addr.sin_addr.s_addr = inet_addr(SERV_IP); s_addr.sin_port = htons(port); if (bind(l_sock, (struct sockaddr*)&s_addr, sizeof(s_addr))) { printf("bind listen socket error %d\n", errno); return 0; } if (listen(l_sock, 20)) { printf("listen error\n"); return 0; } socklen_t c_addr_len = sizeof(c_addr); s_sock = accept(l_sock, (struct sockaddr*)&c_addr, &c_addr_len); if (s_sock < 0) { printf("accept fail\n"); return 0; } else { char ip[16] = { 0 }; inet_ntop(NET_PROTOCAL, &(c_addr.sin_addr), ip, INET_ADDRSTRLEN); printf("accept connection: ip %s port %d\n", ip, c_addr.sin_port); } getsockopt(s_sock, SOL_SOCKET, SO_SNDBUF, &sndbuf_size, &optlen); getsockopt(s_sock, SOL_SOCKET, SO_RCVBUF, &rcvbuf_size, &optlen); printf("server: sndbuf_size %d, rcvbuf_size %d\n", sndbuf_size, rcvbuf_size); send(s_sock, "Request", sizeof("Request"), MSG_NOSIGNAL); recv(s_sock, msg, sizeof(msg), 0); printf("get msg: %s\n", msg); close(s_sock); close(l_sock); return 0; } int main(int argc, char **argv) { bool wrong_param = false; int buf_size = 0, port = 0; int c; while(!wrong_param && (-1 != (c = getopt(argc, argv, "p:s:")))) { switch (c) { case 's': buf_size = atoi(optarg); break; case 'p': port = atoi(optarg); break; case '?': printf("usage: ./server -s -p \n"); wrong_param = true; break; } } if (!wrong_param) net_serv(buf_size, port); return 0; }