#include #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 INADDR_ANY #define SERV_PORT 10012 #define BUF_SIZE (5 * 128 * 1024) int stream_recv(int fd, char *buf, int msgsize) { int n = msgsize; while (n) { int i = read(fd, buf, n); if (i < 0) return i; buf += i; n -= i; if (i == 0) break; //printf("Successfully recv %d B message\n", i); } return msgsize-n; } int net_serv(int port, int msgsize) { int recv; if (!port) port = SERV_PORT; int l_sock = socket(NET_PROTOCAL, SOCK_STREAM, 0); struct sockaddr_in s_addr; memset(&s_addr, 0, sizeof(struct sockaddr_in)); s_addr.sin_family = NET_PROTOCAL; s_addr.sin_addr.s_addr = SERV_IP; s_addr.sin_port = htons(port); // bind listen socket if (bind(l_sock, (struct sockaddr*)&s_addr, sizeof(s_addr))) { printf("bind listen socket error %d\n", errno); return 0; } // listen if (listen(l_sock, 20)) { printf("listen error\n"); return 0; } struct sockaddr_in c_addr; socklen_t c_addr_len = sizeof(c_addr); int 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); } char *buf = (char *)malloc(sizeof(char) * BUF_SIZE); while (1) { if (msgsize > BUF_SIZE) break; //printf("Recv msgsize: %d\n", msgsize); recv = stream_recv(s_sock, buf, msgsize); if (recv <= 0) { if (recv) printf("Error recv %d\n", recv); break; } } printf("done\n"); close(s_sock); close(l_sock); return 0; } int main(int argc, char **argv) { bool wrong_param = false; int msgsize = BUF_SIZE; int port = 0; int c; while(!wrong_param && (-1 != (c = getopt(argc, argv, "p:m:")))) { switch (c) { case 'p': port = atoi(optarg); break; case 'm': msgsize = atoi(optarg); break; case '?': printf("usage: ./server -p -m \n"); wrong_param = true; break; } } if (!wrong_param) net_serv(port, msgsize); return 0; }