地址参数必须为一个指向地址结构的指针。我们将会注意到通常所用的地址类型为sockaddr结构类型。这就意味着我们必须使用C不应该的转换操作符来转换我们所传递的指针类型,从而来满足编译器的要求。下面的例子演示了一个建立网络地址的bind函数。在这里我们注意inet_aton以及bind函数的使用。 /* * af_inet.c * * Demonstrating the bind function * by establishing a Specific AF_INET * Socket address */
/* now bind the address to the socket */ z = bind(sck_inet,(struct sockaddr *)&adr_inet,len_inet);
if(z==-1) { bail("bind()"); } /* display all of our bound sockets */ system("netstat -pa --tcp 2>/dev/null |" "sed -n '1,/^Proto/p;/bind/p'"); close(sck_inet); return 0; } 这个程序的输出结果如下所示: Active Internet connections (servers and established) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 127.0.0.24:9000 *:* CLOSE 934/bind
/* * this function accepts as input a socket * for which a socket address must be * is converted into a string and returned * * if an error occurs,NULL is returned. */ char *sock_addr(int s,char *buf,size_t bufsize) { int z; /* status return code */ struct sockaddr_in adr_inet; /* AF_INET */ int len_inet; /* length */
/* * obtain the address of the socket: */ len_inet = sizeof adr_inet;
z = getsockname(s,(struct sockaddr *)&adr_inet,&len_inet);
if(z==-1) return NULL; /* failed */
/* * convert address into a string * form that can be displayer: */ snprintf(buf,bufsize,"%s:%u", inet_ntoa(adr_inet.sin_addr), (unsigned)ntohs(adr_inet.sin_port)); return buf; }
/* * main program */ int main(int argc,char **argv,char **envp) { int z; /* status return code */ int sck_inet; /* socket */ struct sockaddr_in adr_inet; /* AF_INET */ int len_inet; /* length */ char buf[64]; /* work buffer */
/* * create an IPv4 internet socket: */ sck_inet = socket(AF_INET,SOCK_STREAM,0);
/* * this function accepts as input a socket * for which a peer socket address must be * is converted into a string and returned * * if and error occurs,NULL is returned */ char *peer_addr(int s,char *buf,size_t bufsize) { int z; /* status return code */ struct sockaddr_in adr_inet; /* AF_INET */ int len_inet; /* length */
/* * obtain the address of the socket: */ len_inet = sizeof adr_inet;
z = getpeername(s,(struct sockaddr *)&adr_inet,&len_inet);
if(z==-1) bail("getpeername()");
/* * convert address into a string * form that can be displayed: */ z = snprintf(buf,bufsize,"%s:%u", inet_ntoa(adr_inet.sin_addr), (unsigned)ntohs(adr_inet.sin_port));