帮助此代码(给出 STATUS_ACCESS_VIOLATION )
下面是一段代码,我想显示用户输入的地址的IP地址,但它给了我STATUS_ACCESS_VIOLATION,我不明白其原因。
它编译得很好。这是
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
// Link to ws2_32.lib
#include <winsock2.h>
#include <stdio.h>
#include <stdlib.h>
struct protoent *proto=NULL;
int main(int count, char *strings[])
{
int pid;
struct hostent *host;
struct sockaddr_in addr;
if ( count != 3 )
{
printf("usage: %s <addr> < Adressflag = 0 for name and 1 for IP > /n", strings[0] );
exit(0);
}
if ( count == 3 )
{
int flag = atoi(strings[2]);
printf("flag is %d",flag);
if ( flag == 0)
{
pid = getpid();
proto = getprotobyname("ICMP");
host = gethostbyname(strings[1]);
bzero(&addr, sizeof(addr));
addr.sin_family = host->h_addrtype;
addr.sin_port = 0;
addr.sin_addr.s_addr = *(long*)host->h_addr;
//traceroute(&addr);
printf("IP of %s is %s",host->h_name , host-> h_addr);
}
else
{
}
}
return 0;
}
我在 cygwin 中运行的。有人知道这个错误吗?有人能告诉我我做错了什么吗?
Below is a code where I want to display the ip address of the address entered by the user but it gives me STATUS_ACCESS_VIOLATION and I am not understanding the reason for it.
It compiles fine. Here is it
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
// Link to ws2_32.lib
#include <winsock2.h>
#include <stdio.h>
#include <stdlib.h>
struct protoent *proto=NULL;
int main(int count, char *strings[])
{
int pid;
struct hostent *host;
struct sockaddr_in addr;
if ( count != 3 )
{
printf("usage: %s <addr> < Adressflag = 0 for name and 1 for IP > /n", strings[0] );
exit(0);
}
if ( count == 3 )
{
int flag = atoi(strings[2]);
printf("flag is %d",flag);
if ( flag == 0)
{
pid = getpid();
proto = getprotobyname("ICMP");
host = gethostbyname(strings[1]);
bzero(&addr, sizeof(addr));
addr.sin_family = host->h_addrtype;
addr.sin_port = 0;
addr.sin_addr.s_addr = *(long*)host->h_addr;
//traceroute(&addr);
printf("IP of %s is %s",host->h_name , host-> h_addr);
}
else
{
}
}
return 0;
}
I am running this in cygwin. Is anyone aware of the error and can anyone tell what am I doing wrong ??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您真的需要前面的 * 吗?
这意味着您正在取消引用某些随机地址。
您也不检查主机是否为空。
Do you really need the * on the front?
That means you are de-referencing some random address.
You are also not checking host for null.
您不能仅将
char*
转换为long*
来从字符串中获取数字,而且您可能也不应该取消引用。You can't just cast a
char*
tolong*
to get a number from a string, and you probably shouldn't be dereferencing, either.