Beej’s Guide Network to Programming 系列连载10
5.3. bind() ---在那个端口?
一旦你有一个套接字,你可能要将套接字和机器上的一定的端口关联起来。(如果你想用listen()来侦听一定端口的数据,这是必要一步---比如,开始玩多人网络游戏告诉你要连接到192.168.5.10的3490端口) 使用的端口号是由内核相匹配传入的数据包到某个进程的socket描述符。如果你只想用connect()(因为你是客户端,不是服务器端),那么这个步骤没有必要。但是无论如何,请继续读下去。
下面是他的原型:
#include<sys/types.h>
#include<sys/socket.h>
int bind(intsockfd, struct sockaddr *my_addr, int addrlen);
sockfd是调用 socket() 返回的文件描述符。my_addr 是指向数据结构 struct sockaddr 的指针,它保存你的地址(即端口和 IP 地址) 信息。addlen是这个地址(struct socketaddr)的长度。
简单得很不是吗? 再看看例子:
struct addrinfohints, *res;
int sockfd;
// first, load upaddress structs with getaddrinfo():
memset(&hints,0, sizeof(hints));
hints.ai_family =AF_UNSPEC; // use IPv4 or IPv6, whichever
hints.ai_socktype= SOCK_STREAM; // TCP
hints.ai_flags =AI_PASSIVE; // fill in myIP for me
getaddrinfo(NULL, “3490”, &hints, &res);
// make a socket
sockfd =socket(res->ai_family, res->ai_socktype, res->ai_protocol);
// bind it to theport we passed in to getaddrinfo():
bind(sockfd,res->ai_addr, res->ai_addrlen);
通过使用AI_PASSIVE标志,我告诉程序绑定到运行它的主机的IP 。如果你想绑定到一个特定的本地IP地址,删除AI_PASSIVE然后赋值给getaddrinfo()函数的第一个参数。
bind()如果返回-1表示出错。
讲解旧代码部分省略…
摘自 xiaobin_HLJ80的专栏