本文来自CSDN博客,转载出处:http://blog.csdn.net/wwwsq/archive/2010/08/10/5800790.aspx
server:
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <fcntl.h> #include <endian.h> #include <sys/time.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <arpa/inet.h> #include <netinet/in.h> int main(int argc, char** argv) { if (argc != 2) { printf("Usage:/n %s port/n", argv[0]); return 0; } int port = atoi(argv[1]); int sock = socket(AF_INET, SOCK_STREAM, 0); sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(port); addr.sin_addr.s_addr = 0; int on = 1; setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)); if (bind(sock, (struct sockaddr *) &addr, sizeof(addr)) < 0) { perror("bind"); return 0; } if (listen(sock, 50) < 0) { perror("listen"); return 0; } printf("start listening .../nPress Ctrl+C to quit/n/n"); int count = 0; while (1) { accept(sock, 0, 0); count++; if (count%100 == 0) { printf("accepted: %d/n", count); } } return 0; }
client:
#include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <fcntl.h> #include <endian.h> #include <sys/time.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <arpa/inet.h> #include <netinet/in.h> int main(int argc, char** argv) { if (argc != 3) { printf("Usage:/n %s ip port/n", argv[0]); return 0; } char* ip = argv[1]; int port = atoi(argv[2]); sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(port); addr.sin_addr.s_addr = inet_addr(ip); printf("client running .../nPress Ctrl+C to quit/n/n"); int count = 0; while (1) { int sock = socket(AF_INET, SOCK_STREAM, 0); if (connect(sock, (sockaddr*)&addr, sizeof(addr)) < 0) { perror("connect"); return 0; } close(sock); //usleep(10*1000); count++; if (count%100 == 0) { printf("connected: %d/n", count); } } return 0; }