网络编程的几个结构体

hostent结构体定义如下
   struct hostent {
  
char *h_name;
  
char **h_aliases;
  
int h_addrtype;
  
int h_length;
  
char **h_addr_list;
   };

这里是这个数据结构的详细资料:  
  h_name – 地址的正式名称。 
  h_aliases – 空字节-地址的预备名称的指针。 
  h_addrtype –地址类型; 通常是AF_INET。  
  h_length – 地址的比特长度。 
  h_addr_list – 零字节-主机网络地址指针。网络字节顺序。 

示例:

#include <stdio.h>
#include
<stdlib.h>
#include
<netinet/in.h>
#include
<sys/types.h>
#include
<netdb.h>

int main(int argc, char *argv[])
{
struct hostent *host;
if(argc != 2)
{
printf(
"usage: getip address\n");
exit(
-1);
}
if((host = gethostbyname(argv[1])) == NULL)
{
herror(
"gethostbyname error");
exit(
1);
}
printf(
"Host name:%s\n", host->h_name);
printf(
"IP Address:%s\n", inet_ntoa(*((struct in_addr *)host->h_addr)));
return 0;
}

 protoent结构体
struct protoent {
        char *       p_name; //名称
         char *     p_aliases; //别名
4          short *       p_proto; //编号
5         }

示例:

#include <netdb.h>
main()
{
int number;
struct protoent *protocol;
for(number=0; number<5; number++)
{
protocol
= getprotobynumber(number);
if(protocol == (struct protoent * ) NULL) continue;
printf(
"%2d: %-10s: %-10s\n", protocol->p_proto, protocol->p_name, protocol->p_aliases[0]);
}
}

结构体 in_addr sockaddr_in
struct in_addr{
In_addr_t s_addr;
//32bit的地址
}

struct sockaddr_in
{
unit8_t sin_len;
//
sa_family sin_family; //AF_INET
in_port_t sin_port; //16bit
struct in_addr sin_addr;//32bit
char sin_zero[8];
}

   inet_pton(AF_INET, argv[1], &servaddr.sin_addr);

这里的servaddr是sockaddr_in类型,servaddr.sin_addr是in_addr类型

posted @ 2011-02-23 13:27  macula7  阅读(442)  评论(0编辑  收藏  举报