/* ============================================================================ Name : socket.c Author : Version : Copyright : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/socket.h> #include <netinet/in.h> #include<arpa/inet.h> const int MAXLINE = 1024; int main(void) { int sockfd, clientfd; socklen_t cliaddr_len; struct sockaddr_in server_addr, client_addr; sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd == -1) { perror("出错了"); exit(1); } bzero(&server_addr, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_port = htons(1024); server_addr.sin_addr.s_addr = htonl(INADDR_ANY); int br = bind(sockfd, (struct sockaddr *) &server_addr, sizeof(server_addr)); if (br == -1) { perror("出错了"); exit(1); } if ((listen(sockfd, 20)) == -1) { perror("出错了"); exit(1); } char buf[MAXLINE]; for (;;) { clientfd = accept(sockfd, (struct sockaddr *) &client_addr, &cliaddr_len); printf("server get connection from %s.\n", inet_ntoa( client_addr.sin_addr)); int readize = 0; while ((readize = read(clientfd, buf, MAXLINE)) > 0) { printf("内容:%.*s", readize,buf); printf("长度:%d...\n", readize); } write(clientfd, buf, readize); close(clientfd); } return EXIT_SUCCESS; }