internet_connection_new



  • hi@all
    ich musst den thread hier her verlegen...da man komischer weiße im alten das nicht mehr genau lesen kan...ka was da los ist...

    ok letzter post von webfritzi:

    So, ich hab mich jetzt auch mal schlau gemacht. In den Google-Groups
    habe ich etwas gefunden: HIER. Ergebnis der Google-Suche
    Hab den Code etwas umgemodelt, so dass er
    auf meine Bedürfnisse zugeschnitten ist. Leider habe ich noch ein Problem dabei.
    Das erste Pingen geht wunderbar. Naja, fast, denn der IP-String "lpszIP" wird nur einmal
    ordentlich angezeigt. Dann steht da nur noch scheiße drin. WIESO? Der (Compiler) kann doch
    nicht einfach in meinem Speicher rumpfuschen! Naja, ein zweiter Ping schlägt bei mir auch fehl.

    #include <windows.h> 
    #include <winsock2.h> 
    #include <stdio.h> 
    
    /* Program provided as is.  It might be awful or worse. It may not 
       work tomorrow. For novelty use only - do not mistake for 
       a real program. 
    
         Bernard S. Greenberg bsg@basistech.com    25 May 1995 
         Thanks to Andrew Carlson for revealing the Microsoft ICMP API. 
    
       build: cl ping.c wsock32.lib    (used Microsoft C 9.0 (VC2.0)) 
    
    */ 
    
    typedef struct ip_option_information 
    { 
       UCHAR Ttl; 
       UCHAR Tos; 
       UCHAR Flags; 
       UCHAR OptionsSize; 
       PUCHAR OptionsData; 
    } IP_OPTION_INFORMATION, *PIP_OPTION_INFORMATION; 
    
    typedef struct icmp_echo_reply 
    { 
       ULONG Address; 
       ULONG Status; 
       ULONG RoundTripTime; 
       USHORT DataSize; 
       USHORT Reserved; 
       PVOID Data; 
       IP_OPTION_INFORMATION Options; 
    } ICMP_ECHO_REPLY, *PICMP_ECHO_REPLY; 
    
    typedef HANDLE (*LPICMPCREATEFILE)(VOID); 
    typedef DWORD (*LPICMPSENDECHO)(HANDLE,LONG,LPVOID,WORD,PIP_OPTION_INFORMATION,LPVOID,DWORD,DWORD); 
    typedef BOOL (*LPICMPCLOSEHANDLE)(HANDLE); 
    
    #pragma argsused 
    int main(int argc, char ** argv) 
    { 
        HANDLE hh; 
        DWORD dwv; 
        HINSTANCE module; 
        PHOSTENT host; 
        ULONG addr; 
        WSADATA WSAData; 
        char rbuf[5000]; 
        LPICMPCREATEFILE IcmpCreateFile; 
        LPICMPSENDECHO IcmpSendEcho; 
        LPICMPCLOSEHANDLE IcmpCloseHandle; 
        LPCTSTR lpszHost = TEXT("www.web.de"); 
        char lpszIP[16]; 
    
        if(WSAStartup(MAKEWORD(2,0), &WSAData) != 0) 
        { 
            fprintf (stderr, "Can't start up winsock.\n"); 
            return 0; 
        } 
    
        addr = inet_addr(lpszHost); 
        if(addr == (ULONG)INADDR_NONE) 
        { 
            host = gethostbyname(lpszHost); 
            if(host == NULL) 
            { 
                fprintf (stderr, "Can't figure out host name/ID %s.\n", lpszHost); 
                getchar(); 
                return 0; 
            } 
            addr = *(ULONG*)(*host->h_addr_list); 
            lstrcpy( lpszIP, inet_ntoa(*(in_addr*)&addr)); 
        } 
        else 
            lstrcpy( lpszIP, lpszHost ); 
    
        module = LoadLibrary("ICMP.DLL"); 
        if(module == NULL) 
        { 
            fprintf (stderr, "Can't load module ICMP.DLL\n"); 
            getchar(); 
            return 0; 
        } 
    
        IcmpCreateFile = (LPICMPCREATEFILE)GetProcAddress(module, "IcmpCreateFile"); 
        IcmpSendEcho =  (LPICMPSENDECHO)GetProcAddress(module, "IcmpSendEcho"); 
        IcmpCloseHandle = (LPICMPCLOSEHANDLE)GetProcAddress(module, "IcmpCloseHandle"); 
    
        if ( !IcmpCreateFile || !IcmpSendEcho || !IcmpCloseHandle ) 
        { 
            fprintf(stderr, "Can't find module entry points.\n"); 
            getchar(); 
            return 0; 
        } 
    
        hh = IcmpCreateFile(); 
    
        if(!hh) 
        { 
            fprintf(stderr, "Can't open the icmp handle.\n"); 
            getchar(); 
            return 0; 
        } 
    
        printf ("Ping %s [%s] mit 32 Bytes Daten:\n\n", lpszHost, lpszIP); 
        for(int i = 0; i < 1; i++) 
        { 
           LPVOID reqData = (LPVOID)new BYTE[32]; 
    
           dwv = IcmpSendEcho(hh,                     /* Handle of ICMP "file" */ 
                              addr,                   /* IP address of host */ 
                              reqData,                /* ICMP request data */ 
                              32,                     /* sizeof above */ 
                              NULL,                   /* IP request options TBS */ 
                              rbuf,                   /* reply buffer */ 
                              sizeof(rbuf),           /* size of above */ 
                              3000);                  /* timeout, millisecondsp */ 
    
           for(unsigned int j=0; j<dwv; j++) 
           { 
              ICMP_ECHO_REPLY* er = (ICMP_ECHO_REPLY*)rbuf; 
              printf("Antwort von %s: Bytes=%d Zeit=%dms TTL=%d\n", lpszIP, 32, er->RoundTripTime, er->Options.Ttl); 
           } 
    
           delete reqData; 
        } 
    
        printf ("%s\n", dwv ? "PING!" : "Pffft."); 
    
        IcmpCloseHandle(hh); 
        FreeLibrary(module); 
        WSACleanup(); 
    
        getchar(); 
        return 0; 
    }
    

    code besser zu lesen da: http://rafb.net/paste/results/b3086750.html
    hier kann man code nicht als cpp posten da funzt hier was net!!!

    edit: Google-URL gekürzt und Codetags hinzugefügt. Der rafb-Paste ist bereits verschollen, du solltest es besser hier posten.
    sfds



  • @webfritzi schau mal da:
    http://www.crazylabs.info/crazylabs_download.php?rel=pingStat&app=-v1.1.zip

    da hat auch einer so einen eigenen ping geschrieben..ich kenn mich aber mit rawsockets nicht aus;-( vielleicht kannst du da war rausholen...!??

    cu



  • hi leute!! ich will das mit fets da mit mit ner pipe machen!!! wie impementiere ich das da im meinem pinp?

    mein ping:

    #include <windows.h>
    #include <string> 
    #include <iostream> 
    using namespace std; 
    
    int WinMain(HINSTANCE hInstance, HINSTANCE hPrevIsntance, LPSTR lpCmdine, int nShowCmd)
    {
      WNDCLASS WndClass;
      HWND hWnd;
      MSG Msg;
    
      char* ptr; 
      string command; 
      string ip; 
    
      ptr = new char[512]; 
    
      ip="195.135.220.3"; 
    
      command = "PING " + ip + " -n 1"; 
      FILE *fp= _popen(command.c_str(),"r"); 
    
      sprintf(ptr,command.c_str()); 
    
      while(fgets(ptr,512,fp)!=NULL) 
      { 
        command = ptr; 
        if(command.find("Antwort",0)==0){
          _pclose(fp); 
          delete [] ptr;
          MessageBox(NULL, "Your are offline", "info", MB_OK | MB_ICONINFORMATION);
          return(Msg.wParam); 
        } 
      } 
      _pclose(fp); 
      delete [] ptr; 
      MessageBox(NULL, "Your are online", "info", MB_OK | MB_ICONINFORMATION);
      return(Msg.wParam);
    }
    
    wie kann ich fets über ne pipe realisieren!!!
    so wie da:
    http://www.c-plusplus.net/forum/topic,14249.html
    
    pipe code:
    #include <windows.h> 
    #include <stdlib.h> 
    #include <tchar.h> 
    
    VOID ReadConsoleApplicationHandler(LPSTR lpszBuffer) { 
    MessageBoxA(NULL, lpszBuffer, "Information", MB_OK); 
    } 
    
    BOOL ReadConsoleApplication(LPTSTR lpszApplication, VOID (*lpfnHandler)(LPSTR lpszBuffer)) { 
    HANDLE hOutputReadTemporary = NULL; 
    HANDLE hOutputRead = NULL; 
    HANDLE hOutputWrite = NULL; 
    HANDLE hInputWriteTemporary = NULL; 
    HANDLE hInputRead = NULL; 
    HANDLE hInputWrite = NULL; 
    HANDLE hErrorWrite = NULL; 
    SECURITY_ATTRIBUTES sa = {0}; 
    PROCESS_INFORMATION pi = {0}; 
    STARTUPINFO si = {0}; 
    CHAR lpBuffer[256] = {0}; 
    DWORD nBytesRead = 0; 
    
    sa.nLength = sizeof(SECURITY_ATTRIBUTES); 
    sa.lpSecurityDescriptor = NULL; 
    sa.bInheritHandle = TRUE; 
    
    if(CreatePipe(&hOutputReadTemporary, &hOutputWrite, &sa, 0) == FALSE) { 
    return FALSE; 
    } 
    
    if(DuplicateHandle(GetCurrentProcess(), hOutputWrite, GetCurrentProcess(), 
    &hErrorWrite, 0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE) { 
    return FALSE; 
    } 
    
    if(CreatePipe(&hInputRead, &hInputWriteTemporary, &sa, 0) == FALSE) { 
    return FALSE; 
    } 
    
    if(DuplicateHandle(GetCurrentProcess(), hOutputReadTemporary, GetCurrentProcess(), 
    &hOutputRead, 0, FALSE, DUPLICATE_SAME_ACCESS) == FALSE) { 
    return FALSE; 
    } 
    
    if(DuplicateHandle(GetCurrentProcess(), hInputWriteTemporary, GetCurrentProcess(), 
    &hInputWrite, 0, FALSE, DUPLICATE_SAME_ACCESS) == FALSE) { 
    return FALSE; 
    } 
    
    if(CloseHandle(hOutputReadTemporary) == FALSE) { 
    return FALSE; 
    } 
    
    if(CloseHandle(hInputWriteTemporary) == FALSE) { 
    return FALSE; 
    } 
    
    si.cb = sizeof(STARTUPINFO); 
    si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; 
    si.hStdOutput = hOutputWrite; 
    si.hStdInput = hInputRead; 
    si.hStdError = hErrorWrite; 
    si.wShowWindow = SW_HIDE; 
    
    if(CreateProcess(NULL, lpszApplication, NULL, NULL, TRUE, 
    CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi) == FALSE) { 
    return FALSE; 
    } 
    
    if(CloseHandle(pi.hThread) == FALSE) { 
    return FALSE; 
    } 
    
    if(CloseHandle(hOutputWrite) == FALSE) { 
    return FALSE; 
    } 
    
    if(CloseHandle(hInputRead) == FALSE) { 
    return FALSE; 
    } 
    
    if(CloseHandle(hErrorWrite) == FALSE) { 
    return FALSE; 
    } 
    
    while(TRUE) { 
    if(ReadFile(hOutputRead, lpBuffer, 255, &nBytesRead, NULL) == FALSE) { 
    if(GetLastError() == ERROR_BROKEN_PIPE) { 
    break; 
    } else { 
    return FALSE; 
    } 
    } 
    
    lpBuffer[nBytesRead] = '\0'; 
    lpfnHandler(lpBuffer); 
    } 
    
    if(CloseHandle(hOutputRead) == FALSE) { 
    return FALSE; 
    } 
    
    if(CloseHandle(hInputWrite) == FALSE) { 
    return FALSE; 
    } 
    
    return TRUE; 
    } 
    
    ///////////////////////////////////////////////////// 
    // Application's entry point 
    ///////////////////////////////////////////////////// 
    
    INT WINAPI _tWinMain(HINSTANCE hInstance, 
    HINSTANCE hPreviousInstance, 
    LPTSTR lpszCommandLine, 
    INT nShowState) { 
    
    if(ReadConsoleApplication(TEXT("net.exe"), ReadConsoleApplicationHandler) == FALSE) { 
    MessageBox(NULL, TEXT("ReadConsoleApplication failed!"), TEXT("Information"), MB_OK); 
    return EXIT_FAILURE; 
    } 
    
    return EXIT_SUCCESS; 
    }
    

    cu surf.



  • Ist doch alles Blödsinn. Mach das mit den Sockets.



  • @webfritzi: aso...ja wenn meinst....ok
    frage zu deinem prog. ich hab die wsock32.lib von visual studio 6 oder und bekomm paar error da bei struct usw... normal?
    oder soll ich das rawsockets machen, was das für vor -ode nachteil hat ka!???

    cu surf.



  • In der MSDN/PSDK steht bei den Socket-Funktionen überall:
    Library: Use Ws2_32.lib



  • hab auch diese ws2_32.lib unnd wsock32.lib auch dabei...aber beim compelieren sind paar error mit winsock2.h weiß jemand warum???
    error:

    c:\programme\microsoft visual studio 6\vc98\include\winsock2.h(99) : error C2011: 'fd_set' : 'struct'-Typ-Neudefinition
    c:\programme\microsoft visual studio 6\vc98\include\winsock2.h(134) : warning C4005: 'FD_SET' : Makro-Neudefinition
            c:\programme\microsoft visual studio 6\vc98\include\winsock.h(83) : Siehe vorherige Definition von 'FD_SET'
    c:\programme\microsoft visual studio 6\vc98\include\winsock2.h(143) : error C2011: 'timeval' : 'struct'-Typ-Neudefinition
    c:\programme\microsoft visual studio 6\vc98\include\winsock2.h(199) : error C2011: 'hostent' : 'struct'-Typ-Neudefinition
    c:\programme\microsoft visual studio 6\vc98\include\winsock2.h(212) : error C2011: 'netent' : 'struct'-Typ-Neudefinition
    

    usw usw.....möchte jetzt nicht error flodden!!!
    pingen.exe - 60 Fehler, 12 Warnung(en)

    cu surf.



  • der code wird nicht richtig angezeigt da, deshalb musste ich neu posten!!

    #include <windows.h>
    //#include <winsock2.h>
    #include <stdlib.h>
    #include <iostream.h>
    
    #define ICMP_ECHOREPLY                 0
    #define ICMP_UNREACHABLE               3
    #define ICMP_ECHO                      8
    
    // 0 = Netz nicht erreichbar
    #define ICMP_CODE_NETWORK_UNREACHABLE  0
    // 1 = Rechner nicht erreichbar
    #define ICMP_CODE_HOST_UNREACHABLE     1
    
    // Minimalgrösse 8 Byte
    #define ICMP_MIN            8
    
    #define STATUS_FAILED       0xFFFF
    #define DEF_PACKET_SIZE     32
    #define MAX_PACKET          65000
    
    /*
    Der IP Header:
    --------------
    
    |  Byte 0       |   Byte 1      |  Byte 2       |  Byte 3       |
    
    0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    |Version|  IHL  |Type of Service|          Total Length         |
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    |         Identification        |Flags|      Fragment Offset    |
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    |  Time to Live |    Protocol   |         Header Checksum       |
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    |                       Source Address                          |
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    |                    Destination Address                        |
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    */
    
    struct IP_HEADER
    {
      unsigned int   h_len:4;          // Länge des Headers
      unsigned int   version:4;        // IP Version
      unsigned char  tos;              // Type of service
      unsigned short total_len;        // Gesamt länge des Pakets
      unsigned short ident;            // unique identifier
      unsigned short frag_and_flags;   // flags
      unsigned char  ttl;              // TTL
      unsigned char  proto;            // Protokoll (TCP, UDP etc)
      unsigned short checksum;         // IP Checksumme
      unsigned int   sourceIP;         // Source IP
      unsigned int   destIP;           // Ziel IP
    };
    
    /*
    Der ICMP Header:
    ----------------
    
    |  Byte 0       |   Byte 1      |  Byte 2       |  Byte 3       |
    
    0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    | Type          | Code          |     ICMP Header Prüfsumme     |
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    |Identifikatior |Sequenz Nummer |                               |
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    |                      Timestamp                                |
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    
    */
    
    struct ICMP_HEADER
    {
      char           i_type;    // Type
      char           i_code;    // Code
      unsigned short i_cksum;   // Prüfsumme
      unsigned short i_id;      // Identifikatior
      unsigned short i_seq;     // Sequenz Nummer
      unsigned long  timestamp; // Um die benötigte Zeit zu messen
    };
    
    long WinsockStartup();
    void FillIcmpData(char* icmp_data, int datasize);
    unsigned short checksum(unsigned short *buffer, int size);
    void DecodeResponse(char *buf, int bytes, SOCKADDR_IN *from);
    
    //int main(int argc, char** argv)
    int main()
    {
      SOCKET sockRaw;
      SOCKADDR_IN addrDest;
      SOCKADDR_IN addrFrom;
      int addrFromLen = sizeof(addrFrom);
      HOSTENT* ptrHostent;
      unsigned long datasize;
      int RecvTimeout = 1000;
      char *dest_ip;
      char *icmp_data;
      char *recvbuf;
      unsigned int addr=0;
      unsigned short seq_no = 0;
      int BytesReceived;
      int BytesSent;
      long rc;
      //const char* ip="195.135.220.3";
    
      /*if(argc < 2)
      {
        cout << "Error: To few Arguments " << endl;
        cout << "\nUsage: ping <host> [Bytes to send]" << endl;
        return 0;
      }*/
    
      rc = WinsockStartup();
      if (rc == SOCKET_ERROR)
      {
        cout << "Error: WinsockStartup failed: " << WSAGetLastError() << endl;
        return SOCKET_ERROR;
      }
      sockRaw = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
      if (sockRaw == INVALID_SOCKET)
      {
        cout << "Error: Cannot create Socket: " << WSAGetLastError() << endl;
        return SOCKET_ERROR;
      }
      rc = setsockopt(sockRaw,SOL_SOCKET,SO_RCVTIMEO,(char*)&RecvTimeout, sizeof(RecvTimeout));
      if(rc == SOCKET_ERROR)
      {
        cout << "Error: Cannot set Recv Timeout: " << WSAGetLastError() << endl;
        return SOCKET_ERROR;
      }
    
      ptrHostent = "195.135.220.3";
      /*ptrHostent = gethostbyname(argv[1]);
      if (!ptrHostent)
      {
        addr = inet_addr(argv[1]);
      }*/
    
      if ((!ptrHostent)  && (addr == INADDR_NONE) )
      {
        cout << "Error: Cannot resolve Host: " << WSAGetLastError() << endl;
        return SOCKET_ERROR;
      }
      if (ptrHostent != NULL)
      {
        memcpy(&(addrDest.sin_addr),ptrHostent->h_addr, ptrHostent->h_length);
      }
      else
      {
        addrDest.sin_addr.s_addr = addr;
      }
      if (ptrHostent)
      {
        addrDest.sin_family = ptrHostent->h_addrtype;
      }
      else
      {
        addrDest.sin_family = AF_INET;
      }
    
      // Konvertiert eine Netzwerk Adresse (SOCKADDR_IN) in einen String im Punkt Format (x.x.x.x)
      dest_ip = inet_ntoa(addrDest.sin_addr);
    
      //if (argc >2)
      //{
        datasize = 2;
        //datasize = atoi(argv[2]);
        if (datasize == 0)
        {
          datasize = DEF_PACKET_SIZE;
        }
        if (datasize > MAX_PACKET)
        {
          cout << "Error: Data size more then " << MAX_PACKET << " Bytes or less then 0 Bytes" << endl;
          cout << "I'll take the default size..." << endl;
          datasize = DEF_PACKET_SIZE;
        }
      /*}
      else
      {
        datasize = DEF_PACKET_SIZE;
      }*/
      datasize += sizeof(ICMP_HEADER);
    
      icmp_data = (char*)malloc(MAX_PACKET);
      recvbuf = (char*)malloc(MAX_PACKET+sizeof(IP_HEADER)+sizeof(ICMP_HEADER));
    
      if (!icmp_data || !recvbuf)
      {
        cout << "Error: Not enough Memory: " << GetLastError() << endl;
        return 0;
      }
    
      FillIcmpData(icmp_data,datasize);
    
      while(1)
      {
        ((ICMP_HEADER*)icmp_data)->i_cksum = 0;
        ((ICMP_HEADER*)icmp_data)->timestamp = GetTickCount();
    
        ((ICMP_HEADER*)icmp_data)->i_seq = seq_no++;
        ((ICMP_HEADER*)icmp_data)->i_cksum = checksum((unsigned short*)icmp_data, datasize);
    
        BytesSent = sendto(sockRaw,icmp_data,datasize,0,(SOCKADDR*)&addrDest, sizeof(addrDest));
        if (BytesSent == SOCKET_ERROR)
        {
          if (WSAGetLastError() == WSAETIMEDOUT)
          {
            cout << "timed out\n" << endl;
            continue;
          }
          cout << "sendto failed: " << WSAGetLastError() << endl;
          return 0;
        }
        if (BytesSent < datasize )
        {
          cout <<"Wrote " << BytesSent << " bytes" << endl;
        }
        BytesReceived = recvfrom(sockRaw,recvbuf,MAX_PACKET+sizeof(IP_HEADER)+sizeof(ICMP_HEADER),0,(SOCKADDR*)&addrFrom, &addrFromLen);
        if (BytesReceived == SOCKET_ERROR)
        {
          if (WSAGetLastError() == WSAETIMEDOUT)
          {
            cout << "timed out" << endl;
            continue;
          }
          cout << "recvfrom failed: " << WSAGetLastError() << endl;
          return 0;
        }
        DecodeResponse(recvbuf,BytesReceived,&addrFrom);
        Sleep(1000);
      }
    }
    
    /*
    Die Antwort die wir empfangen ist ein IP Paket. Wir müssen nun den IP
    Header decodieren um die ICMP Daten lesen zu können
    */
    
    void DecodeResponse(char *buf, int bytes, SOCKADDR_IN *from)
    {
      IP_HEADER   *IpHeader;
      ICMP_HEADER *IcmpHeader;
      unsigned short IpHeaderLen;
    
      IpHeader = (IP_HEADER*)buf;
      IpHeaderLen = IpHeader->h_len * 4 ; // number of 32-bit words *4 = bytes
    
      if (bytes  < IpHeaderLen + ICMP_MIN)
      {
        cout << "Too few bytes from " << inet_ntoa(from->sin_addr) << endl;
      }
      IcmpHeader = (ICMP_HEADER*)(buf + IpHeaderLen);
    
      if (IcmpHeader->i_type != ICMP_ECHOREPLY)
      {
        if (IcmpHeader->i_type == ICMP_UNREACHABLE)
        {
          cout << "Reply from " << inet_ntoa(from->sin_addr);
          if(IcmpHeader->i_code == ICMP_CODE_HOST_UNREACHABLE)
          {
            cout << ": Destination Host unreachable !" << endl;
            return;
          }
          if(IcmpHeader->i_code == ICMP_CODE_NETWORK_UNREACHABLE)
          {
            cout << ": Destination Network unreachable !" << endl;
            return;
          }
        }
        else
        {
          cout << "non-echo type " << (int)IcmpHeader->i_type <<" received" << endl;
          return;
        }
      }
    
      if (IcmpHeader->i_id != (unsigned short)GetCurrentProcessId())
      {
        cout << "someone else's packet!" << endl;
        return ;
      }
    
      cout << bytes << " bytes from " << inet_ntoa(from->sin_addr);
      cout << " icmp_seq = " << IcmpHeader->i_seq;
      cout << " time: " << GetTickCount()-IcmpHeader->timestamp << " ms " << endl;
    }
    
    unsigned short checksum(unsigned short *buffer, int size)
    {
      unsigned long cksum=0;
      while(size >1)
      {
        cksum+=*buffer++;
        size -=sizeof(unsigned short);
      }
    
      if(size)
      {
        cksum += *(unsigned char*)buffer;
      }
    
      cksum = (cksum >> 16) + (cksum & 0xffff);
      cksum += (cksum >>16);
      return (unsigned short)(~cksum);
    }
    
    /*
    Hilfs Funktion um unseren ICMP Header zu füllen
    */
    void FillIcmpData(char * icmp_data, int datasize){
    
      ICMP_HEADER *icmp_hdr;
      char *datapart;
    
      icmp_hdr = (ICMP_HEADER*)icmp_data;
    
      icmp_hdr->i_type = ICMP_ECHO;
      icmp_hdr->i_code = 0;
      icmp_hdr->i_id = (unsigned short)GetCurrentProcessId();
      icmp_hdr->i_cksum = 0;
      icmp_hdr->i_seq = 0;
    
      datapart = icmp_data + sizeof(ICMP_HEADER);
      // Den Buffer mit etwas füllen
      memset(datapart,'C', datasize - sizeof(ICMP_HEADER));
    }
    
    long WinsockStartup()
    {
      long rc;
    
      WORD wVersionRequested;
      WSADATA wsaData;
      wVersionRequested = MAKEWORD(2, 1);
    
      rc = WSAStartup( wVersionRequested, &wsaData );
      return rc;
    }
    
    --------------------Konfiguration: pingen1 - Win32 Debug--------------------
    Kompilierung läuft...
    main.cpp
    C:\Dokumente und Einstellungen\Gerald\Desktop\pingen1\main.cpp(138) : error C2440: '=' : 'char [14]' kann nicht in 'struct hostent *' konvertiert werden
            Die Typen, auf die verwiesen wird, sind nicht verwandt; die Konvertierung erfordert einen reinterpret_cast-Operator oder eine Typumwandlung im C- oder Funktionsformat
    C:\Dokumente und Einstellungen\Gerald\Desktop\pingen1\main.cpp(221) : warning C4018: '<' : Konflikt zwischen signed und unsigned
    Fehler beim Ausführen von cl.exe.
    
    pingen1.exe - 1 Fehler, 1 Warnung(en)
    

    der error!??? cu



  • Poste doch bitte erstmal nur die entsprechende Zeile - habe keine Lust zu zählen :p



  • ping ist fertig soweit: wird alles schön in message boxen ausgegeben;-)
    aber ich will noch so ne auswertung machen....wie viele pakete angekommen sind und
    gesendet wurden...so wie bei command.com und dann ping!!!

    was meint ihr zum programm funzt alles bei euch einwandfrei??

    cu surf.

    /******************************************************************************
    
    Programm: Ping
    
    Allgemeines zu ICMP:
    --------------------
    
    Echo Request, Echo Reply
    ------------------------
    
    Diese Meldungen dienen zur Überprüfung ob ein Ziel erreichbar und
    aktiv ist. Der Sender des Echo Request wartet auf eine Echo Reply
    Message, die er nur erhält, wenn der Zielrechner aktiv ist. Als ICMP
    Typ wurde die Nummer 8 für den Request und 0 für den Echo Reply
    definiert. Der Code ist in beiden Fällen auf 0 gesetzt. Außerdem ist ein
    ICMP Echo Identifikator definiert, welcher vom Sender des
    Datagramms erzeugt wird und zur Identifikation des Prozesses dient.
    Der Empfänger schickt den Reply an diesen Port. Eine Echo Sequenz
    Nummer wird zur fortlaufenden Numerierung des Datagramms
    genutzt. Der Empfänger nutzt die Nummer bei der Antwort und
    ermöglicht dem Sender des Echo Request die Überprüfung der
    Richtigkeit der Antwort. Die ICMP Echo Daten enthalten einen Echo
    String, der vom Empfänger an den Sender zurückgeschickt wird.
    
    Destination Unreachable
    -----------------------
    
    Diese Nachricht wird an den Sender des Datagramms geschickt,
    wenn ein Subnetzwerk oder Router den Zielrechner nicht erreichen
    kann oder das Paket nicht ausgeliefert werden kann weil das Don´t
    Fragment Bit gesetzt ist und das Paket für ein Netzwerk zu groß ist.
    Die Nachricht wird vom Router generiert sofern es sich um ein nicht
    erreichbares Netzwerk oder einen unerreichbaren Zielrechner handelt.
    Sollte es sich jedoch um einen unerreichbaren Port handeln so schickt
    diese Meldung der Zielrechner.
    
    ICMP Typ
    
    Zur Unterscheidung der einzelnen ICMP Meldungen wurden ICMP
    Nummern definiert. Die Destination Unreachable Meldung hat die
    Nummer 3.
    
    ICMP Code
    
    Der ICMP Code teilt dem Sender mit, weshalb sein Datagramm nicht
    übermittelt werden konnte. Es sind die folgenden Destination
    Unreachable Codes definiert:
    
    0= Netz nicht erreichbar
    1= Rechner nicht erreichbar
    2= Protokoll nicht erreichbar
    3= Port nicht erreichbar
    4= Fragmentierung notwendig, jedoch nicht möglich wegen gesetztem DF Bit
    5= Source Route nicht erreichbar
    
    ******************************************************************************/
    
    #include <windows.h> 
    #include <stdlib.h>
    #include <string> 
    #include <sstream> 
    #include <iostream>
    #include <stdio.h>
    #include <iostream.h> 
    
    using namespace std;
    
    #define ICMP_ECHOREPLY                 0 
    #define ICMP_UNREACHABLE               3 
    #define ICMP_ECHO                      8 
    
    // 0 = Netz nicht erreichbar 
    #define ICMP_CODE_NETWORK_UNREACHABLE  0 
    // 1 = Rechner nicht erreichbar 
    #define ICMP_CODE_HOST_UNREACHABLE     1 
    
    // Minimalgrösse 8 Byte 
    #define ICMP_MIN            8 
    
    #define STATUS_FAILED       0xFFFF 
    #define DEF_PACKET_SIZE     32 
    #define MAX_PACKET          65000 
    
    /* 
    Der IP Header: 
    -------------- 
    
    |  Byte 0       |   Byte 1      |  Byte 2       |  Byte 3       | 
    
    0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 
    |Version|  IHL  |Type of Service|          Total Length         | 
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 
    |         Identification        |Flags|      Fragment Offset    | 
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 
    |  Time to Live |    Protocol   |         Header Checksum       | 
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 
    |                       Source Address                          | 
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 
    |                    Destination Address                        | 
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 
    */ 
    
    struct IP_HEADER 
    { 
      unsigned int   h_len:4;          // Länge des Headers 
      unsigned int   version:4;        // IP Version 
      unsigned char  tos;              // Type of service 
      unsigned short total_len;        // Gesamt länge des Pakets 
      unsigned short ident;            // unique identifier 
      unsigned short frag_and_flags;   // flags 
      unsigned char  ttl;              // TTL 
      unsigned char  proto;            // Protokoll (TCP, UDP etc) 
      unsigned short checksum;         // IP Checksumme 
      unsigned int   sourceIP;         // Source IP 
      unsigned int   destIP;           // Ziel IP 
    }; 
    
    /* 
    Der ICMP Header: 
    ---------------- 
    
    |  Byte 0       |   Byte 1      |  Byte 2       |  Byte 3       | 
    
    0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 
    | Type          | Code          |     ICMP Header Prüfsumme     | 
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 
    |Identifikatior |Sequenz Nummer |                               | 
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 
    |                      Timestamp                                | 
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 
    
    */ 
    
    struct ICMP_HEADER 
    { 
      char           i_type;    // Type 
      char           i_code;    // Code 
      unsigned short i_cksum;   // Prüfsumme 
      unsigned short i_id;      // Identifikatior 
      unsigned short i_seq;     // Sequenz Nummer 
      unsigned long  timestamp; // Um die benötigte Zeit zu messen 
    }; 
    
    long WinsockStartup(); 
    void FillIcmpData(char* icmp_data, int datasize); 
    unsigned short checksum(unsigned short *buffer, int size); 
    void DecodeResponse(char *buf, int bytes, SOCKADDR_IN *from);
    
    // Für Messagebox Ausgabe
    ostringstream os; 
    
    int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevIsntance, LPSTR lpCmdine, int nShowCmd)
    {
      WNDCLASS WndClass;
      HWND hWnd;
      MSG Msg;
    
      SOCKET sockRaw; 
      SOCKADDR_IN addrDest; 
      SOCKADDR_IN addrFrom; 
      int addrFromLen = sizeof(addrFrom); 
      HOSTENT* ptrHostent; 
      unsigned long datasize; 
      int RecvTimeout = 1000; 
      char *dest_ip; 
      char *icmp_data; 
      char *recvbuf; 
      unsigned int addr=0; 
      unsigned short seq_no = 0; 
      int BytesReceived; 
      int BytesSent; 
      long rc; 
      unsigned ping_anzahl=0;
      // Die IP fuer anpingen: http://suse.de
      const char* ip="195.135.220.3"; 
    
      rc = WinsockStartup(); 
      if (rc == SOCKET_ERROR) 
      { 
    	os << "Error: WinsockStartup failed: " << WSAGetLastError(); 
    	MessageBox(NULL, os.str().c_str(), "info", MB_OK | MB_ICONINFORMATION);
    	os.str("");
        return SOCKET_ERROR; 
      } 
      sockRaw = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); 
      if (sockRaw == INVALID_SOCKET) 
      { 
    	os << "Error: Cannot create Socket: " << WSAGetLastError(); 
    	MessageBox(NULL, os.str().c_str(), "info", MB_OK | MB_ICONINFORMATION);
    	os.str("");
        return SOCKET_ERROR; 
      } 
      rc = setsockopt(sockRaw,SOL_SOCKET,SO_RCVTIMEO,(char*)&RecvTimeout, sizeof(RecvTimeout)); 
      if(rc == SOCKET_ERROR) 
      { 
    	os << "Error: Cannot set Recv Timeout: " << WSAGetLastError();
    	MessageBox(NULL, os.str().c_str(), "info", MB_OK | MB_ICONINFORMATION);
    	os.str("");
        return SOCKET_ERROR; 
      } 
    
      // Ip Adresse in ptrHostent geben
      ptrHostent = gethostbyname(ip); 
    
      if ((!ptrHostent)  && (addr == INADDR_NONE) ) 
      { 
    	os << "Error: Cannot resolve Host: " << WSAGetLastError(); 
    	MessageBox(NULL, os.str().c_str(), "info", MB_OK | MB_ICONINFORMATION);
        return SOCKET_ERROR; 
      } 
      if (ptrHostent != NULL) 
      { 
        memcpy(&(addrDest.sin_addr),ptrHostent->h_addr, ptrHostent->h_length); 
      } 
      else 
      { 
        addrDest.sin_addr.s_addr = addr; 
      } 
      if (ptrHostent) 
      { 
        addrDest.sin_family = ptrHostent->h_addrtype; 
      } 
      else 
      { 
        addrDest.sin_family = AF_INET; 
      } 
    
      // Konvertiert eine Netzwerk Adresse (SOCKADDR_IN) in einen String im Punkt Format (x.x.x.x) 
      dest_ip = inet_ntoa(addrDest.sin_addr); 
    
      // Gröss des Datenpaketes
      datasize = 32; 
    
      if (datasize == 0) 
      { 
         datasize = DEF_PACKET_SIZE; 
      } 
    
      if (datasize > MAX_PACKET) 
      { 
         os << "Error: Data size more then " << MAX_PACKET << " Bytes or less then 0 Bytes"; 
         MessageBox(NULL, os.str().c_str(), "info", MB_OK | MB_ICONINFORMATION);
    	 os.str("");
    
    	 os << "I'll take the default size...";
    	 MessageBox(NULL, os.str().c_str(), "info", MB_OK | MB_ICONINFORMATION);
    	 os.str("");
         datasize = DEF_PACKET_SIZE; 
      } 
    
      datasize += sizeof(ICMP_HEADER); 
    
      icmp_data = (char*)malloc(MAX_PACKET); 
      recvbuf = (char*)malloc(MAX_PACKET+sizeof(IP_HEADER)+sizeof(ICMP_HEADER)); 
    
      if (!icmp_data || !recvbuf) 
      { 
    	os << "Error: Not enough Memory: " << GetLastError(); 
        MessageBox(NULL, os.str().c_str(), "info", MB_OK | MB_ICONINFORMATION);
    	os.str("");
        return 0; 
      } 
    
      FillIcmpData(icmp_data,datasize); 
    
      os << "Ping wird ausgefuehrt fuer " << ip << " mit " << datasize << " Bytes Daten";
      MessageBox(NULL, os.str().c_str(), "info", MB_OK | MB_ICONINFORMATION);
      os.str("");
    
      while(ping_anzahl<4) 
      { 
        ((ICMP_HEADER*)icmp_data)->i_cksum = 0; 
        ((ICMP_HEADER*)icmp_data)->timestamp = GetTickCount(); 
    
        ((ICMP_HEADER*)icmp_data)->i_seq = seq_no++; 
        ((ICMP_HEADER*)icmp_data)->i_cksum = checksum((unsigned short*)icmp_data, datasize); 
    
        BytesSent = sendto(sockRaw,icmp_data,datasize,0,(SOCKADDR*)&addrDest, sizeof(addrDest)); 
        if (BytesSent == SOCKET_ERROR) 
        { 
          if (WSAGetLastError() == WSAETIMEDOUT) 
          { 
    		os << "timed out"; 
            MessageBox(NULL, os.str().c_str(), "info", MB_OK | MB_ICONINFORMATION);
    		os.str("");
            continue; 
          } 
    	  os << "sendto failed: " << WSAGetLastError();
    	  MessageBox(NULL, os.str().c_str(), "info", MB_OK | MB_ICONINFORMATION);
    	  os.str("");
          return 0; 
        } 
        if (BytesSent < datasize ) 
        { 
    	   os <<"Wrote " << BytesSent << " bytes";
    	   MessageBox(NULL, os.str().c_str(), "info", MB_OK | MB_ICONINFORMATION);	
           os.str("");
    	} 
        BytesReceived = recvfrom(sockRaw,recvbuf,MAX_PACKET+sizeof(IP_HEADER)+sizeof(ICMP_HEADER),0,(SOCKADDR*)&addrFrom, &addrFromLen); 
        if (BytesReceived == SOCKET_ERROR) 
        { 
          if (WSAGetLastError() == WSAETIMEDOUT) 
          { 
    		os << "timed out"; 
    		MessageBox(NULL, os.str().c_str(), "info", MB_OK | MB_ICONINFORMATION);
    		os.str("");
            continue; 
          } 
    	  os << "recvfrom failed: " << WSAGetLastError();
    	  MessageBox(NULL, os.str().c_str(), "info", MB_OK | MB_ICONINFORMATION);
    	  os.str("");
          return 0; 
        } 
        DecodeResponse(recvbuf,BytesReceived,&addrFrom); 
        Sleep(1000);
    	ping_anzahl++;
      } 
    
      return(Msg.wParam);
    } 
    
    /* 
    Die Antwort die wir empfangen ist ein IP Paket. Wir müssen nun den IP 
    Header decodieren um die ICMP Daten lesen zu können 
    */ 
    
    void DecodeResponse(char *buf, int bytes, SOCKADDR_IN *from) 
    { 
      IP_HEADER   *IpHeader; 
      ICMP_HEADER *IcmpHeader; 
      unsigned short IpHeaderLen; 
    
      IpHeader = (IP_HEADER*)buf; 
      IpHeaderLen = IpHeader->h_len * 4 ; // number of 32-bit words *4 = bytes 
    
      if (bytes  < IpHeaderLen + ICMP_MIN) 
      { 
    	 os << "Too few bytes from " << inet_ntoa(from->sin_addr);
    	 MessageBox(NULL, os.str().c_str(), "info", MB_OK | MB_ICONINFORMATION);
    	 os.str("");
      } 
      IcmpHeader = (ICMP_HEADER*)(buf + IpHeaderLen); 
    
      if (IcmpHeader->i_type != ICMP_ECHOREPLY) 
      { 
        if (IcmpHeader->i_type == ICMP_UNREACHABLE) 
        { 
    	  os << "Reply from " << inet_ntoa(from->sin_addr);
    	  MessageBox(NULL, os.str().c_str(), "info", MB_OK | MB_ICONINFORMATION);
    	  os.str("");
          if(IcmpHeader->i_code == ICMP_CODE_HOST_UNREACHABLE) 
          { 
    		os << ": Destination Host unreachable !"; 
    		MessageBox(NULL, os.str().c_str(), "info", MB_OK | MB_ICONINFORMATION);
    		os.str("");
            return; 
          } 
          if(IcmpHeader->i_code == ICMP_CODE_NETWORK_UNREACHABLE) 
          { 
    		os << ": Destination Network unreachable !";
    		MessageBox(NULL, os.str().c_str(), "info", MB_OK | MB_ICONINFORMATION);
    		os.str("");
            return; 
          } 
        } 
        else 
        { 
    	  os << "non-echo type " << (int)IcmpHeader->i_type <<" received";
    	  MessageBox(NULL, os.str().c_str(), "info", MB_OK | MB_ICONINFORMATION);
    	  os.str("");
          return; 
        } 
      } 
    
      if (IcmpHeader->i_id != (unsigned short)GetCurrentProcessId()) 
      { 
    	os << "someone else's packet!" << endl;
    	MessageBox(NULL, os.str().c_str(), "info", MB_OK | MB_ICONINFORMATION);
    	os.str("");
        return ; 
      } 
    
      os << bytes << " bytes from " << inet_ntoa(from->sin_addr);
      os << " icmp_seq = " << IcmpHeader->i_seq;
      os << " time: " << GetTickCount()-IcmpHeader->timestamp << " ms ";
      MessageBox(NULL, os.str().c_str(), "info", MB_OK | MB_ICONINFORMATION);
      os.str("");
    } 
    
    unsigned short checksum(unsigned short *buffer, int size) 
    { 
      unsigned long cksum=0; 
      while(size >1) 
      { 
        cksum+=*buffer++; 
        size -=sizeof(unsigned short); 
      } 
    
      if(size) 
      { 
        cksum += *(unsigned char*)buffer; 
      } 
    
      cksum = (cksum >> 16) + (cksum & 0xffff); 
      cksum += (cksum >>16); 
      return (unsigned short)(~cksum); 
    } 
    
    /* 
    Hilfs Funktion um unseren ICMP Header zu füllen 
    */ 
    void FillIcmpData(char * icmp_data, int datasize){ 
    
      ICMP_HEADER *icmp_hdr; 
      char *datapart; 
    
      icmp_hdr = (ICMP_HEADER*)icmp_data; 
    
      icmp_hdr->i_type = ICMP_ECHO; 
      icmp_hdr->i_code = 0; 
      icmp_hdr->i_id = (unsigned short)GetCurrentProcessId(); 
      icmp_hdr->i_cksum = 0; 
      icmp_hdr->i_seq = 0; 
    
      datapart = icmp_data + sizeof(ICMP_HEADER); 
      // Den Buffer mit etwas füllen 
      memset(datapart,'C', datasize - sizeof(ICMP_HEADER)); 
    } 
    
    long WinsockStartup() 
    { 
      long rc; 
    
      WORD wVersionRequested; 
      WSADATA wsaData; 
      wVersionRequested = MAKEWORD(2, 1); 
    
      rc = WSAStartup( wVersionRequested, &wsaData ); 
      return rc; 
    }
    


  • Setzte doch bitte nicht immer wieder den ganzen Code ins Forum - Schreib es von mir aus einmal rein und editiere es dann



  • @flenders: sorry mach ich nun....
    wenn wer den pinger getestet hat..bitte antworten!

    cu surf.



  • Habs getestet. Erstens dauert das Pingen sehr lange (immer so um die 700 ms), und zweitens bekomme ich nach 3-4 Malen eine AccessViolation.



  • WebFritzi schrieb:

    Habs getestet. Erstens dauert das Pingen sehr lange (immer so um die 700 ms), und zweitens bekomme ich nach 3-4 Malen eine AccessViolation.

    @webfritzi:
    komisch, komisch....dann ich hab grad noch mal getestet mein prog braucht so im schnitt 60-80ms fürs pingen und ich hab habs so eingestellt das er 4 mal datenpakete zum server schickt...so wies der command.com ping auch tut!!
    und accessvoilation hab ich auch nie!! hast due den richtigen code? denn ich versteh das nicht ganz...wo gibs accessvoilation?

    cu surf.


Anmelden zum Antworten