将ip地址的字符串表示转为二进制数字形式:
IPV4:
int inet_aton(const char *strptr,struct in_addr *addrptr); //返回:1字符串有效,0字符串无效
in_addr_t inet_addr(const char *strptr);
char *inet_ntoa(struct in_addr inaddr);
IPV4和IPV6通用:
int inet_pton(int family,const char *strptr,void *addrptr);
const char *inet_ntop(int family,const void *addrptr,char *strptr,size_t len);
套接口相关函数:
int socket(int family,int type,int protocol);
int connect(int sockfd, const struct sockaddr *servaddr, socklen_t addrlen); //servaddr contain server's IP address and port
int bind(int sockfd, const struct sockaddr *myaddr, socklen_t addrlen);
//bind可以指定一个端口号,指定一个IP地址,可以两者都指定,也可以一个也不指定。当服务器启动时,要捆绑总所周知的端口,比如FTP服务要捆绑21端口。如果TCP客户或服务器不调用bind,当调用函数connect或listen时,内核就要为套接口选择一个临时端口。让内核来选择临时端口,这对TCP客户来说是正常的,除非应用要求一个预留端口;但对TCP服务来说是极少见的,因为服务器的端口是要让大家知道的。对于不调用bind的TCP客户,当connect成功返回后,可以用getsockname返回内核分配给此连接的本地IP地址和本地端口号。对于以INADDR_ANY和端口号0调用bind后,getsockname返回由内核分配的IP地址和本地端口号。
//myaddr中的sin_addr如果为htonl(INADDR_ANY),则bind不为套接口指定IP地址,myaddr中的sin_port如果为0,则bind不为套接口指定端口。
//myaddr里面指定的IP地址必须是主机的一个接口。对于TCP服务器,这限制了套接口只接收那些目的地为此IP的客户连接。TCP客户一般不把IP地址捆绑到它自己的套接口上面。TCP客户在连接套接口时,由内核根据所用的输出接口来选择源IP地址。
int listen(int sockfd, int backlog)
//listen将未连接的套接口转换成被动套接口,指示内核应接受指向此套接口的连接请求。
//backlog的含义没有正式的定义,最原始的定义在4.2BSD 中的手册中,定义它位待处理连接可能增长的最大书目。但未解释什么是待处理的连接。
int accept(int sockfd, struct sockaddr *cliaddr, socklen_t *addrlen);
int close(int sockfd);