Linux 网络编程一步一步学(五)-开启网络监听服务
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <errno.h> 4 #include <string.h> 5 #include <sys/types.h> 6 #include <netinet/in.h> 7 #include <sys/socket.h> 8 #include <sys/wait.h> 9 #include <unistd.h> 10 #include <arpa/inet.h> 11 int main(int argc, char **argv) - 12 { | 13 int sockfd; | 14 struct sockaddr_in my_addr; | 15 unsigned int myport, lisnum; | 16 if (argv[1]) | 17 myport = atoi(argv[1]); | 18 else | 19 myport = 7838; | 20 if (argv[2]) | 21 lisnum = atoi(argv[2]); | 22 else | 23 lisnum = 2; | 24 sockfd = socket(PF_INET, SOCK_STREAM, 0); | 25 bzero(&my_addr, sizeof(my_addr)); | 26 my_addr.sin_family = PF_INET; | 27 my_addr.sin_port = htons(myport); | 28 if(argv[3]) | 29 my_addr.sin_addr.s_addr = inet_addr(argv[3]); | 30 else | 31 my_addr.sin_addr.s_addr = INADDR_ANY; | 32 bind(sockfd, (struct sockaddr *) &my_addr, sizeof(struct sockaddr)); - 33 if (listen(sockfd, lisnum) == -1) { 2 34 perror("listen"); 2 35 exit(1); 2 36 } | 37 else printf("begin listen\n"); | 38 sleep(100); | 39 close(sockfd); | 40 return 0; | 41 }