Partage
  • Partager sur Facebook
  • Partager sur Twitter

Api winsock 2 GetTcpTable probleme de linkage ?

Lister les connections sur la machine

Sujet résolu
    22 juin 2020 à 6:53:12

    Bonjours,


    Je compte lister les connection, je ne maitrise pas le C (gros débutant) en revanche je connai le c++. certe c est different et pour j'avance un peux a l'aveugle car il ne me faut pas grand chose, a savoir juste l'api de microsoft qui est GetTcpsTable


    Le lien https://docs.microsoft.com/en-us/windows/win32/api/iphlpapi/nf-iphlpapi-gettcptable

    J'espere avoir le bon sdk , le erreur lier aux pragma son igniorée car je me demande si le linkage est fait correctement.

    le code servant d'exemple  est le meme que sur la page citée pour je le replace pour le besoins .


    #include <stdio.h>
    #include <stdlib.h>
    // Need to link with Iphlpapi.lib and Ws2_32.lib
    #include <winsock2.h>
    #include <ws2tcpip.h>
    #include <iphlpapi.h>
    
    
    #pragma comment(lib, "iphlpapi.lib")
    #pragma comment(lib, "ws2_32.lib")
    
    #define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
    #define FREE(x) HeapFree(GetProcessHeap(), 0, (x))
    
    /* Note: could also use malloc() and free() */
    
    int main()
    {
    
        // Declare and initialize variables
        PMIB_TCPTABLE pTcpTable;
        DWORD dwSize = 0;
        DWORD dwRetVal = 0;
    
        char szLocalAddr[128];
        char szRemoteAddr[128];
    
        struct in_addr IpAddr;
    
        int i;
    
        pTcpTable = (MIB_TCPTABLE *) MALLOC(sizeof (MIB_TCPTABLE));
        if (pTcpTable == NULL) {
            printf("Error allocating memory\n");
            return 1;
        }
    
        dwSize = sizeof (MIB_TCPTABLE);
    // Make an initial call to GetTcpTable to
    // get the necessary size into the dwSize variable
        if ((dwRetVal = GetTcpTable(pTcpTable, &dwSize, TRUE)) ==
            ERROR_INSUFFICIENT_BUFFER) {
            FREE(pTcpTable);
            pTcpTable = (MIB_TCPTABLE *) MALLOC(dwSize);
            if (pTcpTable == NULL) {
                printf("Error allocating memory\n");
                return 1;
            }
        }
    // Make a second call to GetTcpTable to get
    // the actual data we require
        if ((dwRetVal = GetTcpTable(pTcpTable, &dwSize, TRUE)) == NO_ERROR) {
            printf("\tNumber of entries: %d\n", (int) pTcpTable->dwNumEntries);
            for (i = 0; i < (int) pTcpTable->dwNumEntries; i++) {
                IpAddr.S_un.S_addr = (u_long) pTcpTable->table[i].dwLocalAddr;
                strcpy_s(szLocalAddr, sizeof (szLocalAddr), inet_ntoa(IpAddr));
                IpAddr.S_un.S_addr = (u_long) pTcpTable->table[i].dwRemoteAddr;
                strcpy_s(szRemoteAddr, sizeof (szRemoteAddr), inet_ntoa(IpAddr));
    
                printf("\n\tTCP[%d] State: %ld - ", i,
                       pTcpTable->table[i].dwState);
                switch (pTcpTable->table[i].dwState) {
                case MIB_TCP_STATE_CLOSED:
                    printf("CLOSED\n");
                    break;
                case MIB_TCP_STATE_LISTEN:
                    printf("LISTEN\n");
                    break;
                case MIB_TCP_STATE_SYN_SENT:
                    printf("SYN-SENT\n");
                    break;
                case MIB_TCP_STATE_SYN_RCVD:
                    printf("SYN-RECEIVED\n");
                    break;
                case MIB_TCP_STATE_ESTAB:
                    printf("ESTABLISHED\n");
                    break;
                case MIB_TCP_STATE_FIN_WAIT1:
                    printf("FIN-WAIT-1\n");
                    break;
                case MIB_TCP_STATE_FIN_WAIT2:
                    printf("FIN-WAIT-2 \n");
                    break;
                case MIB_TCP_STATE_CLOSE_WAIT:
                    printf("CLOSE-WAIT\n");
                    break;
                case MIB_TCP_STATE_CLOSING:
                    printf("CLOSING\n");
                    break;
                case MIB_TCP_STATE_LAST_ACK:
                    printf("LAST-ACK\n");
                    break;
                case MIB_TCP_STATE_TIME_WAIT:
                    printf("TIME-WAIT\n");
                    break;
                case MIB_TCP_STATE_DELETE_TCB:
                    printf("DELETE-TCB\n");
                    break;
                default:
                    printf("UNKNOWN dwState value\n");
                    break;
                }
                printf("\tTCP[%d] Local Addr: %s\n", i, szLocalAddr);
                printf("\tTCP[%d] Local Port: %d \n", i,
                       ntohs((u_short)pTcpTable->table[i].dwLocalPort));
                printf("\tTCP[%d] Remote Addr: %s\n", i, szRemoteAddr);
                printf("\tTCP[%d] Remote Port: %d\n", i,
                       ntohs((u_short)pTcpTable->table[i].dwRemotePort));
            }
        } else {
            printf("\tGetTcpTable failed with %d\n", dwRetVal);
            FREE(pTcpTable);
            return 1;
        }
    
        if (pTcpTable != NULL) {
            FREE(pTcpTable);
            pTcpTable = NULL;
        }
    
        return 0;
    }
    

    les 'erreur qui surviennes:


    ||=== Build: Debug in Projet_en_c (compiler: GNU GCC Compiler) ===|
    C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\um\winnt.h|1035|error: #error Must define a target architecture.|
    C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\um\winnt.h|1408|error: unknown type name 'EXCEPTION_DISPOSITION'|
    C:\CodeBlocks\MinGW\include\excpt.h|68|error: conflicting types for 'EXCEPTION_REGISTRATION_RECORD'|
    C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\um\winnt.h|11480|note: previous declaration of 'EXCEPTION_REGISTRATION_RECORD' was here|
    C:\CodeBlocks\MinGW\include\excpt.h|69|error: conflicting types for 'PEXCEPTION_REGISTRATION_RECORD'|
    C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\um\winnt.h|11482|note: previous declaration of 'PEXCEPTION_REGISTRATION_RECORD' was here|
    C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\um\propidlbase.h|568|error: array type has incomplete element type 'struct tagPROPVARIANT'|
    C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\um\propidlbase.h|574|error: array type has incomplete element type 'struct tagPROPVARIANT'|
    ||=== Build failed: 6 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
    

    c'est peut etre pas le bon sdk aussi ?? 

    Merci de m'avoir lu et de votre patience


    • Partager sur Facebook
    • Partager sur Twitter
      22 juin 2020 à 10:35:51

      Les pragma de link sont destinés à Visual Studio. Sous MinGW il faut faire les links dans ton projet ou ton makefile... selon comment tu compiles. Comme en C++.

      Je viens de tester l'exemple, il fonctionne sous MinGW. (si les strcpy_s t'embête, tu les remplaces par des strcpy). 

      • Partager sur Facebook
      • Partager sur Twitter
        22 juin 2020 à 10:54:55

        Merci pour ta réponse tu peux me dire si ton sdk est en 32 ou 64 et si tu est ien sur un windows 10 ? 

        c'est le même sdk  que j'ai pris ici:https://developer.microsoft.com/fr-fr/windows/downloads/windows-10-sdk/

        Car chez moi ça miaule pas mal donc je ne sai pas du tout si c' est le bon sdk ou mon code block mingw ou moi qui fait du n'importe quoi ?

        edit:

        c'est bien un projet consol et les option du compilateur en mode C mai le compilateur est celuis-ci  mingw32-g++.exe ?

        ou il faut que je le change ?

        si tu pouvai me coller les path que tu a mis cela pourrai fortement m'aider merci :)

        -
        Edité par XiouzanaxyXeon 22 juin 2020 à 11:13:33

        • Partager sur Facebook
        • Partager sur Twitter
          22 juin 2020 à 11:51:01

          Je n'ai pas pris de SDK, puisque c'est déjà inclus avec MinGW,

          je suis sur Windows 7 (la version de Windows n'a rien a voir avec les erreur de compilations).

          Celui que tu sites est destiné au outils de Microsoft, je ne pense pas qu'il passe sous MinGw.

          Oui c'est bien un projet Console C. 

          • Partager sur Facebook
          • Partager sur Twitter
            22 juin 2020 à 11:53:18

            Apres un rester des option des option du compilateur (est-ce suffisant ?)

            'ai bien une erreur comme tu le souligne

            main.cpp|56|error: 'strcpy_s' was not declared in this scope|

            J'ai donc changer et %a donne ceci:

            ||=== Build: Debug in dev_list (compiler: GNU GCC Compiler) ===|
            C:\Users\Xerox\Documents\Devcpp\dev_list\main.cpp|9|warning: ignoring #pragma comment  [-Wunknown-pragmas]|
            C:\Users\Xerox\Documents\Devcpp\dev_list\main.cpp|10|warning: ignoring #pragma comment  [-Wunknown-pragmas]|
            C:\Users\Xerox\Documents\Devcpp\dev_list\main.cpp||In function 'int main()':|
            C:\Users\Xerox\Documents\Devcpp\dev_list\main.cpp|56|error: invalid conversion from 'unsigned int' to 'const char*' [-fpermissive]|
            C:\Users\Xerox\Documents\Devcpp\dev_list\main.cpp|56|error: too many arguments to function 'char* strcpy(char*, const char*)'|
            C:\CodeBlocks\MinGW\include\string.h|45|note: declared here|
            C:\Users\Xerox\Documents\Devcpp\dev_list\main.cpp|58|error: invalid conversion from 'unsigned int' to 'const char*' [-fpermissive]|
            C:\Users\Xerox\Documents\Devcpp\dev_list\main.cpp|58|error: too many arguments to function 'char* strcpy(char*, const char*)'|
            C:\CodeBlocks\MinGW\include\string.h|45|note: declared here|
            C:\Users\Xerox\Documents\Devcpp\dev_list\main.cpp|111|warning: format '%d' expects argument of type 'int', but argument 2 has type 'DWORD {aka long unsigned int}' [-Wformat=]|
            ||=== Build failed: 4 error(s), 3 warning(s) (0 minute(s), 0 second(s)) ===|
            



            • Partager sur Facebook
            • Partager sur Twitter
              22 juin 2020 à 13:32:02

              strcpy ne prend que deux arguments : la destination et la source ! 

              char* strcpy(char *dest, const char *src);

              Pour afficher un DWORD c'est "%lu" au lieu de "%d"

              • Partager sur Facebook
              • Partager sur Twitter
                22 juin 2020 à 18:49:43

                je comprend pas j'ai ajouter #include <string.h> et il ne reconnai quand meme pas la déclaration donc la je ne comprend pas ???

                strcpy_s(szLocalAddr, sizeof (szLocalAddr), inet_ntoa(IpAddr));

                supporte donc 3 arguement raison pour la qu'elle il est utiliser ici. il a un probleme de conversion avec strcpy  donc sa déplace le probleme 

                Je me demande si le compilateur est bien adapter tu as quelle version s'il te plaît ?



                • Partager sur Facebook
                • Partager sur Twitter
                  22 juin 2020 à 20:46:54

                  La différence, c'est que strcpy_s reçois la taille du buffer et pas strcpy.

                  Donc avec strcpy_s c'est :

                  strcpy_s(szLocalAddr, sizeof (szLocalAddr), inet_ntoa(IpAddr));

                  et avec strcpy c'est :

                  strcpy(szLocalAddr, inet_ntoa(IpAddr));

                  XiouzanaxyXeon a écrit:

                  Je me demande si le compilateur est bien adapter tu as quelle version s'il te plaît ?

                  Vu les erreurs qu'il te reste, il devrait y avaler !

                  Je l'ai compilé avec 2 versions une 64 bit 8.1 et une 32 bits 5.1 assez ancienne, les deux fonctionnent.Mais avec des erreur comme cela faut plutôt chercher dans le code que mettre ça sur le dos du compilateur.

                  -
                  Edité par rouloude 22 juin 2020 à 21:12:05

                  • Partager sur Facebook
                  • Partager sur Twitter
                    23 juin 2020 à 5:16:12

                    Merci pour ta réponse, bon j'ai placer les fichier suivant dans le répertoir ou ce trouve le projet
                    un dir donne ceci:
                    IPHLPAPI.DLL
                    iphlpapi.lib
                    main.c
                    obj
                    Projet_en_c.cbp
                    Projet_en_c.layout
                    WS2_32.Lib
                    Dans les options:
                    compilateur-->linker setting-->other linker options
                    -lws2_32
                    l'erreur a changer:
                    |11|warning: ignoring #pragma comment  [-Wunknown-pragmas]|
                    |12|warning: ignoring #pragma comment  [-Wunknown-pragmas]|
                    ||In function 'int main()':|
                    |115|warning: format '%d' expects argument of type 'int', but argument 2 has type 'DWORD {aka long unsigned int}' [-Wformat=]|
                    obj\Debug\main.o||In function `main':|
                    |43|undefined reference to `GetTcpTable@12'|
                    |54|undefined reference to `GetTcpTable@12'|
                    ||error: ld returned 1 exit status|
                    ||=== Build failed: 3 error(s), 3 warning(s) (0 minute(s), 0 second(s)) ===|
                    je ne sai pas si cela est correct ce que je fait ?, il manque peux être autre chose mai j'ai rien trouver de plus pour le moment ?
                    enfin d'apres la doc c'est bien (les bon  fichier ?) il ne miaule pas sur les includes donc il les trouves  ,
                    Cepandant
                    undefined reference to
                    ne semble pas pris en charge par les fichier ??
                    j'utilise code block 17.12 et il me semble que c est un version 5.0 de gcc / g++
                    Merci pour ta réponse
                    • Partager sur Facebook
                    • Partager sur Twitter
                      23 juin 2020 à 9:38:38

                      La dll fait partie de Windows, elle est donc déjà sur ton PC, les fichier lib c'est pour Visual Studio. Tu n'as donc aucun fichier à rajouter dans ton dossier.

                      Je t'ai déjà dit plus haut que ton SDK, tu n'en a pas besoin, c'est celui de Visual Studio. MinGW a déjà tout ça d'inclus.  

                      Toi il te faut linker les fichiers .a de MinGW  iphlpapi.a  et  ws2_32.a   c'est tout. Les options de link c'est -liphlpapi  et  -lws2_32

                      Tu devrais regarder un cours sur les processus de compilation, ça t'aiderait beaucoup.

                      -
                      Edité par rouloude 23 juin 2020 à 11:08:23

                      • Partager sur Facebook
                      • Partager sur Twitter
                        23 juin 2020 à 13:08:40

                        Merci  beacoup pour l'information et ta patience,  si tu as un lien pour le cour je suis preneur , car j'ai quand meme 3 livre  dedier aux c++ mai rien n'aborde vraiment les libraries exterieur

                        Le sujet est résolut 

                        -
                        Edité par XiouzanaxyXeon 23 juin 2020 à 13:09:58

                        • Partager sur Facebook
                        • Partager sur Twitter

                        Api winsock 2 GetTcpTable probleme de linkage ?

                        × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
                        × Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.
                        • Editeur
                        • Markdown