bind函数
? ? ? ? ? ? ? ? ? 學網絡編程不得不提到bind函數,bind函數的作用不言而喻,就是給套接字取一個姓名。在生活中,姓氏代表家族,名表示你是家族的哪個人。在網絡中也是這樣,IP標識主機,進程標識端口。所以要給套接字綁定一個IP和端口,不然誰認識你,特別是服務端。客戶端隨后說。
?
[mapan@localhost test]$ ls server.cpp [mapan@localhost test]$ cat server.cpp #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <errno.h> #include <malloc.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/ioctl.h> #include <stdarg.h> #include <fcntl.h> #include <sys/types.h> #include <sys/wait.h> #include <netinet/in.h> #include <arpa/inet.h> #include <signal.h> #define MAXLINE 4096void main() {int listenfd,connfd;pid_t childpid;socklen_t clilen;struct sockaddr_in cliaddr,servaddr;listenfd=socket(AF_INET,SOCK_STREAM,0);bzero(&servaddr,sizeof(servaddr));servaddr.sin_family=AF_INET;servaddr.sin_addr.s_addr=htonl(INADDR_ANY);servaddr.sin_port=htons(8888);bind(listenfd,(struct sockaddr *)&servaddr,sizeof(servaddr)); listen(listenfd,5);getchar();close(listenfd); } [mapan@localhost test]$ g++ server.cpp [mapan@localhost test]$ ./a.out?
?
?
打開另外一個窗口:
?
[mapan@localhost ~]$ netstat -na | grep 8888 tcp 0 0 0.0.0.0:8888 0.0.0.0:* LISTEN [mapan@localhost ~]$?
套接字綁定到IP為0.0.0.0,端口為8888。服務端的套接字是需要綁定的,為啥呢?服務端端嘛,提供的服務的,總要告訴別人提供服務地點在哪里,別人容易找啊,對就是這個道理。
?
?
?
總結
- 上一篇: 两个不同的文件相互引用全局变量
- 下一篇: listen函数