直接上代码,gcc编译即可,带一个参数,即需要侦听的端口号。
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #define MAXLINE 4096 /*max text line length*/ #define LISTENQ 8 /*maximum number of client connections*/ void main(int argc, char *argv[]) { int sockfd, portno, connfd, n; socklen_t clilen; char buf[MAXLINE]; struct sockaddr_in cliaddr, servaddr; if (argc < 2) { fprintf(stderr, "[ERROR] no port number provided, usage: po portno\n"); exit(1); } portno = atoi(argv[1]); //creation of the socket sockfd = socket (AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { fprintf(stderr, "[ERROR] failed on opening socket\n"); exit(1); } //preparation of the socket address servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(portno); if (bind(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) { fprintf(stderr, "[ERROR] failed on binding\n"); exit(1); } listen(sockfd, LISTENQ); printf("%s\n","[INFO] server running, waiting for connections..."); for ( ; ; ) { clilen = sizeof(cliaddr); connfd = accept(sockfd, (struct sockaddr *) &cliaddr, &clilen); if (connfd < 0) { fprintf(stderr, "[ERROR] failed on accept\n"); } else { printf("%s\n","[INFO] received request...\n"); while ((n = recv(connfd, buf, MAXLINE,0)) > 0) { printf("%s","[INFO] string received from and resent to the client:\n"); puts(buf); send(connfd, buf, n, 0); } if (n < 0) { fprintf(stderr, "[ERROR] failed on read\n"); exit(1); } close(connfd); } } //close listening socket close(sockfd); }
代码来源于Google搜索,做了一些修改和调整。