请高手帮忙看下

shawn 2011-01-05 03:49:18

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <windows.h>
void GetIpAddrList(char *pServerName)
{
struct hostent *ipList;
Sleep(100);
ipList = gethostbyname(pServerName);
if(ipList != NULL)
{
while(*ipList->h_addr_list != NULL)
{
struct in_addr tempAddr;
memcpy(&tempAddr,*ipList->h_addr_list,sizeof(struct in_addr));
printf("%s\n",inet_ntoa(tempAddr));
ipList->h_addr_list++;
}
}
}
int main()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;

wVersionRequested = MAKEWORD( 2, 2 );

err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 )
{
/* Tell the user that we could not find a usable */
/* WinSock DLL. */
return;
}

/* Confirm that the WinSock DLL supports 2.2.*/
/* Note that if the DLL supports versions greater */
/* than 2.2 in addition to 2.2, it will still return */
/* 2.2 in wVersion since that is the version we */
/* requested. */

if ( LOBYTE( wsaData.wVersion ) != 2 ||
HIBYTE( wsaData.wVersion ) != 2 )
{
/* Tell the user that we could not find a usable */
/* WinSock DLL. */
WSACleanup( );
return;
}

FILE *pData = fopen("data.txt","r+b");
if(pData == NULL)
{
exit(EXIT_FAILURE);
}
char szBuf[BUFSIZ];

while(1)
{
memset(szBuf,0,BUFSIZ);
if(fgets(szBuf,BUFSIZ,pData))
{
if(szBuf[strlen(szBuf)-1] == '\n')
szBuf[strlen(szBuf) -1] = '\0';
printf("%s\n",szBuf);
GetIpAddrList(szBuf);
}
else
break;
}
fclose(pData);
// GetIpAddrList("www.baidu.com");
// GetIpAddrList("www.sina.com.cn");
// GetIpAddrList("www.sohu.com");
getchar();
return 0;
}


想让各位高手帮忙看下,为什么通过注释的部分可以显示对应域名的ip,而通过我这种方式只能获取最后一个域名的ip地址呢?我的data.txt的内容是:
www.baidu.com
www.sina.com.cn
www.sohu.com
请大虾帮忙看下 。。。
...全文
84 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
shawn 2011-01-05
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 matrixcl 的回复:]

改成这样就能适应两种行结束符了
C/C++ code

while(1)
{
memset(szBuf,0,BUFSIZ);
if(fgets(szBuf,BUFSIZ,pData))
{
int nLen = strlen(szBuf);
if (nLen >= 2 &&……
[/Quote]
okay,谢谢 ~
matrixcl 2011-01-05
  • 打赏
  • 举报
回复
改成这样就能适应两种行结束符了

while(1)
{
memset(szBuf,0,BUFSIZ);
if(fgets(szBuf,BUFSIZ,pData))
{
int nLen = strlen(szBuf);
if (nLen >= 2 && szBuf[nLen-2] == '\r' && szBuf[nLen-1] == '\n')
szBuf[nLen - 2] = '\0';
else if(nLen >= 1 && szBuf[nLen-1] == '\n')
szBuf[nLen - 1] = '\0';
printf("%s\n",szBuf);
GetIpAddrList(szBuf);
}
else
break;
}
matrixcl 2011-01-05
  • 打赏
  • 举报
回复
windows下一般的文本编译器(如记事本)保存的文本文件,换行符是"\r\n"而不是"\n"

所以你传入gethostbyname的参数后面多了一个\r,无法识别导致失败。
hai040 2011-01-05
  • 打赏
  • 举报
回复
fopen("data.txt","r+b");
用b方式打开,gets可能会有问题

还有这个是多余的,正常的话不会取到\n,取到了要去掉也要-2
if(szBuf[strlen(szBuf)-1] == '\n')

69,369

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧