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 4096


void 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。服务端的套接字是需要绑定的,为啥呢?服务端端嘛,提供的服务的,总要告诉别人提供服务地点在哪里,别人容易找啊,对就是这个道理。

 

 

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

盼盼编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值