开发者

Help with this code ( gives a STATUS_ACCESS_VIOLATION )

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_addrty开发者_高级运维pe;
         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 ??


Do you really need the * on the front?

addr.sin_addr.s_addr = *(long*)host->h_addr

That means you are de-referencing some random address.

You are also not checking host for null.


addr.sin_addr.s_addr = *(long*)host->h_addr

You can't just cast a char* to long* to get a number from a string, and you probably shouldn't be dereferencing, either.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜