LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 1119|回复: 2

请教gethostbyname()和gethostbyaddr()函数的使用,有程序片段

[复制链接]
发表于 2006-4-14 10:12:09 | 显示全部楼层 |阅读模式
小弟刚刚开始学习网络编程,现在想实现一个简单的http请求字段的发送,不过在调试的时候总出现问题
57              printf("\n\nWe get url= %s\n",url);
(gdb) s
We get url= 218.106.129.12:80/index.html
58              printf("The host name= %s\n",host_pos);
(gdb)s
The host name= 218.106.129.12
59              printf("The port number= %d\n",port);
(gdb)s
The port number= 80
60              printf("Want to open file= %s\n",file_pos);
(gdb)s
Want to open file= /index.html
64              if((clitsd=socket(AF_INET,SOCK_STREAM,0))<0){
(gdb)s
68              he=(struct hostent *)malloc(500);
(gdb)s
69              if(inet_aton(host_pos,&servaddr.sin_addr)!=0){  //IP address
(gdb) p he
$1 = (struct hostent *) 0x88d20a0   ----------------->这应该是hostent结构分配的地址吧
(gdb) p *he
$2 = {h_name = 0x0, h_aliases = 0x0, h_addrtype = 0, h_length = 0, h_addr_list = 0x0}
(gdb) p host_pos  ------------------------>这是要解析的IP地址
$3 = 0x88d2038 "218.106.129.12"
(gdb) s                  ------------------------>我想调用gethostbyaddr看看解析的对不对
70                      he=gethostbyaddr((char *)&servaddr.sin_addr,4,AF_INET);
(gdb)s
71                      printf("The information of IP address: %s\n",host_pos);
(gdb) p he   --------------------------------->为什么hostent结构的地址变成0x0呢?
$4 = (struct hostent *) 0x0
(gdb) p *he
Cannot access memory at address 0x0
(gdb)


求大家不要笑话,刚看书学习中......
 楼主| 发表于 2006-4-14 10:15:52 | 显示全部楼层
看起来不方便,我把这段的代码copy一下
//testing
printf("\n\nWe get url= %s\n",url);
printf("The host name= %s\n",host_pos);
printf("The port number= %d\n",port);
printf("Want to open file= %s\n",file_pos);
//======================================
if((clitsd=socket(AF_INET,SOCK_STREAM,0))<0){
                perror("socket error!\n");
                exit(1);
}
he=(struct hostent *)malloc(500);
if(inet_aton(host_pos,&servaddr.sin_addr)!=0){  //IP address
                he=gethostbyaddr((char *)&servaddr.sin_addr,4,AF_INET);
                printf("The information of IP address: %s\n",host_pos);
}else{
                he=gethostbyname(host_pos);
                printf("The information of character address: %s\n",host_pos);
}

if(he==NULL){
                perror("invalid address!\n");
                exit(1);
}
回复 支持 反对

使用道具 举报

发表于 2006-4-19 10:07:35 | 显示全部楼层

gethostbyname()和gethostbyaddr()返回值

返回值都是指向static data,
也就事说,malloc是不需要的.
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表