1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <fcntl.h> #include <unistd.h> #include <netinet/tcp.h> #include <netdb.h> #include <errno.h>
int main(int argc, const char * argv[]) { printf("Hello, World!\n"); int server_sockfd; int client_sockfd; int len; struct sockaddr_in my_add; struct sockaddr_in remote_addr; socklen_t sin_size; char buf[BUFSIZ]; memset(&my_add,0,sizeof(my_add)); my_add.sin_family = AF_INET; my_add.sin_addr.s_addr = INADDR_ANY; my_add.sin_port = htons(8000); if((server_sockfd=socket(PF_INET, SOCK_STREAM, 0))<0) { perror("socket"); return 1; } if (bind(server_sockfd, (struct sockaddr *)&my_add, sizeof(struct sockaddr))<0) { perror("bind"); return 1; } listen(server_sockfd, 5); sin_size = sizeof(struct sockaddr_in); if ((client_sockfd=accept(server_sockfd, (struct sockaddr *)&remote_addr, &sin_size))<0) { perror("accept"); return 1; } printf("accept client %s\n",inet_ntoa(remote_addr.sin_addr)); len = send(client_sockfd, "welcome to my server", 21, 0); while ((len=recv(client_sockfd, buf, BUFSIZ, 0))>0) { buf[len]='\0'; printf("receive:%s\n",buf); if (send(client_sockfd, buf, len, 0)<0) { perror("write"); return 1; } } close(client_sockfd); close(server_sockfd); return 0; }
|