欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

bind函数

发布时间:2025/6/15 37 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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。服务端的套接字是需要绑定的,为啥呢?服务端端嘛,提供的服务的,总要告诉别人提供服务地点在哪里,别人容易找啊,对就是这个道理。

 

 

 

总结

以上是生活随笔为你收集整理的bind函数的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。