Addresse broadcast c++

Résolu
Bonjour,
je veux un code me retournant ou m affichant l addresse de broadcast de mon reseau en c++
merci
Configuration: Windows 7
Safari 532.5

13 réponses

  1. Contributeur
    tu peux ececuter la commande ipconfig (si t'es sous windows), recuperer pour chaque reseau l'ip et le masque, et ainsi calculer l'adresse de broadcast
    0
    1. merci pour la reponse en faite je conne cette comande mais je ne savais pas que l on pouve executer des commandes systeme en c++ comment doi je mis prendre pour recuperer les info de ipconfig
      0
      1. Contributeur
        je vais me faire taper sur les doigts, il parait que c'est pas bien d'utiliser cette fonction, mais je te la fille quand meme:
        http://www.cplusplus.com/reference/cstdlib/system/

        il me semblait qu'on pouvait récuperer le contenu, mais la visiblement il ne renvoit pas de tableau... (à la différence de la fonction équivalente en C++)

        donc ce que je te conseille de faire, c'est d'envoyer ta reponse directement dans un fichier texte avec l'opérateur > (ca donnera donc ca comme commande ipconfig>fichier.txt )
        et ensuite, t'ira lire ton fichier, et le supprimer...

        il y a certainement une manière plus élégante de faire ceci, genre se conencter à une API reseau et recuperer les parametres IP locales
        0
        1. prefere vivement la deuxieme solution et je rejette la premiere car franchement trop zarbie mais merci quand meme j ai trouve un moyen de recuperer laddress ip et le masque de sous reseau now vait cree un convertisseur qui me calculera le broadcast
          Merci
          0
          1. Contributeur
            donne ta solution STP, ça peut toujours servir (et ça m'intéresse).
            0
            1. Contributeur
              tiens char... ca fait quelques années que je me dis qu'il faut que je m'interesse à la capture de trames... et en cherchant des trucs sur libpcap ce matin, je suis tombé la dessus.... ca donne les info (j'ai pas testé)...

              ca necessite d'inclure libpcap, mais au moins c'est plus propre que ma precedente solution:
              http://yuba.stanford.edu/~casado/pcap/section1.html
              0
              1. Contributeur
                Ok, simple et efficace. Mais pas standard :-(
                Merci.
                0
                1. Contributeur
                  j'attend comme toi la solution qu'il dit avoir trouvé ...
                  0
                  1. Oui je ne sais pas si je me suis bien exprime en disant que je prefere la seconde solution mais voila moi sa regle presque mon probleme sa me retourne mon addresse ip et le masque de sous reseau

                    voici le code je compile avc visual studio
                    
                    #include <winsock2.h>
                    #include <ws2tcpip.h>
                    // Link to          Iphlpapi.lib
                    #include <iphlpapi.h>
                    #include <stdio.h>
                    #include <iostream>
                    
                    #pragma comment(lib,"ws2_32.lib")
                    #pragma comment(lib,"Iphlpapi.lib")
                    
                     
                    // Note: could also use malloc() and free()
                    #define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
                    #define FREE(x) HeapFree(GetProcessHeap(), 0, (x))
                     
                    int  main()
                    {
                        int i;
                        // Variables used by GetIpAddrTable
                        PMIB_IPADDRTABLE pIPAddrTable;
                        DWORD dwSize = 0;
                        DWORD dwRetVal = 0;
                        IN_ADDR IPAddr;
                        // Variables used to return error message
                        LPVOID lpMsgBuf;
                     
                        // Before calling AddIPAddress we use GetIpAddrTable to get
                        // an adapter to which we can add the IP.
                        pIPAddrTable = (MIB_IPADDRTABLE *) MALLOC(sizeof (MIB_IPADDRTABLE));
                     
                        if (pIPAddrTable)
                        {
                            // Make an initial call to GetIpAddrTable to get the
                            // necessary size into the dwSize variable
                            if (GetIpAddrTable(pIPAddrTable, &dwSize, 0) == ERROR_INSUFFICIENT_BUFFER)
                            {
                                printf("Not enough space, re-allocate...\n");
                                FREE(pIPAddrTable);
                                pIPAddrTable = (MIB_IPADDRTABLE *) MALLOC(dwSize);
                     
                                if (pIPAddrTable == NULL)
                                {
                                     printf("Memory re-allocation failed for GetIpAddrTable()\n");
                                     exit(1);
                                }
                                else
                                     printf("Memory re-allocation for GetIpAddrTable() is OK!\n");
                             }
                             else
                                  printf("Buffer is sufficient...\n");
                        }
                     
                        // Make a second call to GetIpAddrTable to get the actual data we want
                        if ( (dwRetVal = GetIpAddrTable( pIPAddrTable, &dwSize, 0 )) != NO_ERROR )
                        {
                            printf("GetIpAddrTable() failed with error %d\n", dwRetVal);
                            if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
                                    FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwRetVal,
                                        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),       // Default language
                                              (LPTSTR) & lpMsgBuf, 0, NULL))
                            {
                                printf("\tError: %s", lpMsgBuf);
                                LocalFree(lpMsgBuf);
                            }
                            exit(1);
                        }
                        else
                             printf("GetIpAddrTable() should be fine!\n");
                     
                        printf("\n\tNumber of entries: %ld\n", pIPAddrTable->dwNumEntries);
                        for (i=0; i < (int) pIPAddrTable->dwNumEntries; i++)
                        {
                            printf("\n\tInterface Index[%d]:\t%ld\n", i, pIPAddrTable->table[i].dwIndex);
                            IPAddr.S_un.S_addr = (u_long) pIPAddrTable->table[i].dwAddr;
                            printf("\tIP Address[%d]:     \t%s\n", i, inet_ntoa(IPAddr) );
                            IPAddr.S_un.S_addr = (u_long) pIPAddrTable->table[i].dwMask;
                            printf("\tSubnet Mask[%d]:    \t%s\n", i, inet_ntoa(IPAddr) );
                            IPAddr.S_un.S_addr = (u_long) pIPAddrTable->table[i].dwBCastAddr;
                    		printf("\tBroadCast[%d]:      \t%s (%ld%) \n", i, inet_ntoa(IPAddr), pIPAddrTable->table[i].dwBCastAddr);
                            printf("\tReassembly size[%d]:\t%ld\n", i, pIPAddrTable->table[i].dwReasmSize);
                            printf("\tType and State[%d]:", i);
                     
                    
                            printf("\n");
                        }
                     
                        // Clean up/reset
                        if (pIPAddrTable)
                        {
                            FREE(pIPAddrTable);
                            pIPAddrTable = NULL;
                        }
                     
                        return 0;
                    }
                    
                    
                    0
                    1. Bon j implemente le calcul du broadcast mais en decimal ( pour info l ordinateur l accepte c a d \\192.168.1.255 n a pas de diference avec \\4278298816) j ai du lire un petit cour sur le net pour savoir comment se calcule le broadcast en faisant un ou binaire puis un Et binaire

                      l addresse reseau s obtient en faisant un ET binaire entre address ip de la machine et de address du mask reseau
                      net_addr = host_addr & net_mask;
                      puis le broadcast en faisant un OU binaire de address reseau et l inverse des bit du masque
                      dir_bcast_addr = net_addr | (~net_mask);

                      bon faut que je trouve un autre cour pour le transforme en forme xxx.xxx.xxx.xxx genre 192.168.1.1
                      voici deja le code

                      
                      #include <winsock2.h>
                      #include <ws2tcpip.h>
                      #include <iphlpapi.h>
                      #include <stdio.h>
                      #include <iostream>
                      
                      #pragma comment(lib,"ws2_32.lib")
                      #pragma comment(lib,"Iphlpapi.lib")
                      
                      using namespace std;
                      
                       
                      // Note: could also use malloc() and free()
                      #define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
                      #define FREE(x) HeapFree(GetProcessHeap(), 0, (x))
                       
                      
                      u_long	give_the_broadcast()
                      {
                      	int	i;
                      	u_long host_addr;
                      	u_long net_mask;
                      	u_long net_addr;
                      	u_long dir_bcast_addr;
                      
                      
                          // Variables used by GetIpAddrTable
                          PMIB_IPADDRTABLE pIPAddrTable;
                          DWORD dwSize = 0;
                          DWORD dwRetVal = 0;
                          IN_ADDR IPAddr;
                          // Variables used to return error message
                          LPVOID lpMsgBuf;
                       
                          // Before calling AddIPAddress we use GetIpAddrTable to get
                          // an adapter to which we can add the IP.
                          pIPAddrTable = (MIB_IPADDRTABLE *) MALLOC(sizeof (MIB_IPADDRTABLE));
                       
                          if (pIPAddrTable)
                          {
                              // Make an initial call to GetIpAddrTable to get the
                              // necessary size into the dwSize variable
                              if (GetIpAddrTable(pIPAddrTable, &dwSize, 0) == ERROR_INSUFFICIENT_BUFFER)
                              {
                                  printf("Not enough space, re-allocate...\n");
                                  FREE(pIPAddrTable);
                                  pIPAddrTable = (MIB_IPADDRTABLE *) MALLOC(dwSize);
                       
                                  if (pIPAddrTable == NULL)
                                  {
                                       printf("Memory re-allocation failed for GetIpAddrTable()\n");
                                       exit(1);
                                  }
                                  else
                                       printf("Memory re-allocation for GetIpAddrTable() is OK!\n");
                               }
                               else
                                    printf("Buffer is sufficient...\n");
                          }
                       
                          // Make a second call to GetIpAddrTable to get the actual data we want
                          if ( (dwRetVal = GetIpAddrTable( pIPAddrTable, &dwSize, 0 )) != NO_ERROR )
                          {
                              printf("GetIpAddrTable() failed with error %d\n", dwRetVal);
                              if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
                                      FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwRetVal,
                                          MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),       // Default language
                                                (LPTSTR) & lpMsgBuf, 0, NULL))
                              {
                                  printf("\tError: %s", lpMsgBuf);
                                  LocalFree(lpMsgBuf);
                              }
                              exit(1);
                          }
                          else
                               printf("GetIpAddrTable() should be fine!\n");
                       
                          printf("\n\tNumber of entries: %ld\n", pIPAddrTable->dwNumEntries);
                          for (i=0; i < (int) pIPAddrTable->dwNumEntries; i++)
                          {
                            
                              IPAddr.S_un.S_addr = (u_long) pIPAddrTable->table[i].dwAddr;
                      		host_addr =  inet_addr(inet_ntoa(IPAddr));
                              printf("\tIP Address[%d]:     \t%s\n", i, inet_ntoa(IPAddr) );
                      
                              IPAddr.S_un.S_addr = (u_long) pIPAddrTable->table[i].dwMask;
                      		net_mask = inet_addr(inet_ntoa(IPAddr));
                              printf("\tSubnet Mask[%d]:    \t%s\n", i, inet_ntoa(IPAddr) );
                             
                      		 net_addr = host_addr & net_mask;  
                      
                      		 dir_bcast_addr = net_addr | (~net_mask);
                      
                      		 cout << "\t broadcast = \t\t" << dir_bcast_addr << endl;
                      		
                              printf("\n");
                      
                          }
                       
                          // Clean up/reset
                          if (pIPAddrTable)
                          {
                              FREE(pIPAddrTable);
                              pIPAddrTable = NULL;
                          }
                       
                          return (dir_bcast_addr);
                      }
                      
                      
                      
                      int  main()
                      {
                      	u_long broadcast;
                      
                      	broadcast = give_the_broadcast();
                      
                      	cout << "L addresse en decimal du broadcast est \n" << broadcast<< endl;
                      	
                      }
                       
                      
                      


                      Pour gagner du temps s il y en a un parmis vous qui a fait du reseau , s il peut poster comment faire pour passer du decimal au IPV4 merci .
                      Je pense que se n est pas complique sufi de declarer 4 variables
                      et de shifter le broadcast genre
                      1ervar = add_broad >> 16;

                      bon je n ai pas encore lu sa car en ce qui me concerne l addresse du broadcast en decimal permet de faire fonctioner mon programme mais j aurais aime avoir des explications merci;
                      0
                      1. Contributeur
                        Merci pour la solution. Dommage c'est du 100% windows :-(
                        Il existe des fonctions toutes faites pour mettre en forme une adresse réseau.
                        http://www.manpagez.com/man/3/inet_ntoa/
                        inet_ntoa devrai fonctionné.
                        sinon, avec des snprintf et des opérations binaires :
                        I1.I2.I3.I4
                        int I1=add_broad && \0xff000000;
                        int I2=add_broad && \0x00ff0000;
                        etc.
                        0
                        1. Merci j ai teste tes operations binaires que j ai essaye d affiche avec cout mais sa ne marche pas elle m affiche 1 partout j ai utilise cout car snprintf deja que je ne sais pas l utiliser ne marche par sous windows
                          Pour le inet_ntoa sa marche merci
                          0
                          1. Voici le code final avec l affichage du broadcast en IVP4 j ai pas teste mais je pensse que sous linux c est juste les library que tu va change

                            
                            #include <winsock2.h>
                            #include <ws2tcpip.h>
                            #include <iphlpapi.h>
                            #include <stdio.h>
                            #include <iostream>
                            
                            #pragma comment(lib,"ws2_32.lib")
                            #pragma comment(lib,"Iphlpapi.lib")
                            
                            using namespace std;
                            
                             
                            // Note: could also use malloc() and free()
                            #define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
                            #define FREE(x) HeapFree(GetProcessHeap(), 0, (x))
                             
                            
                            u_long	give_the_broadcast()
                            {
                            	int	i;
                            	u_long host_addr;
                            	u_long net_mask;
                            	u_long net_addr;
                            	u_long dir_bcast_addr;
                            
                            
                                // Variables used by GetIpAddrTable
                                PMIB_IPADDRTABLE pIPAddrTable;
                                DWORD dwSize = 0;
                                DWORD dwRetVal = 0;
                                IN_ADDR IPAddr;
                                // Variables used to return error message
                                LPVOID lpMsgBuf;
                             
                                // Before calling AddIPAddress we use GetIpAddrTable to get
                                // an adapter to which we can add the IP.
                                pIPAddrTable = (MIB_IPADDRTABLE *) MALLOC(sizeof (MIB_IPADDRTABLE));
                             
                                if (pIPAddrTable)
                                {
                                    // Make an initial call to GetIpAddrTable to get the
                                    // necessary size into the dwSize variable
                                    if (GetIpAddrTable(pIPAddrTable, &dwSize, 0) == ERROR_INSUFFICIENT_BUFFER)
                                    {
                                        printf("Not enough space, re-allocate...\n");
                                        FREE(pIPAddrTable);
                                        pIPAddrTable = (MIB_IPADDRTABLE *) MALLOC(dwSize);
                             
                                        if (pIPAddrTable == NULL)
                                        {
                                             printf("Memory re-allocation failed for GetIpAddrTable()\n");
                                             exit(1);
                                        }
                                        else
                                             printf("Memory re-allocation for GetIpAddrTable() is OK!\n");
                                     }
                                     else
                                          printf("Buffer is sufficient...\n");
                                }
                             
                                // Make a second call to GetIpAddrTable to get the actual data we want
                                if ( (dwRetVal = GetIpAddrTable( pIPAddrTable, &dwSize, 0 )) != NO_ERROR )
                                {
                                    printf("GetIpAddrTable() failed with error %d\n", dwRetVal);
                                    if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
                                            FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwRetVal,
                                                MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),       // Default language
                                                      (LPTSTR) & lpMsgBuf, 0, NULL))
                                    {
                                        printf("\tError: %s", lpMsgBuf);
                                        LocalFree(lpMsgBuf);
                                    }
                                    exit(1);
                                }
                                else
                                     printf("GetIpAddrTable() should be fine!\n");
                             
                                printf("\n\t Number of entries: %ld\n", pIPAddrTable->dwNumEntries);
                                for (i=0; i < (int) pIPAddrTable->dwNumEntries; i++)
                                {
                                  
                                    IPAddr.S_un.S_addr = (u_long) pIPAddrTable->table[i].dwAddr;
                            		host_addr =  inet_addr(inet_ntoa(IPAddr));
                                    printf("\t IP Address[%d]:     \t\t%s\n", i, inet_ntoa(IPAddr) );
                            
                                    IPAddr.S_un.S_addr = (u_long) pIPAddrTable->table[i].dwMask;
                            		net_mask = inet_addr(inet_ntoa(IPAddr));
                                    printf("\t Subnet Mask[%d]:    \t\t%s\n", i, inet_ntoa(IPAddr) );
                                   
                            		 net_addr = host_addr & net_mask;  
                            
                            		 dir_bcast_addr = net_addr | (~net_mask);
                            
                            		 cout << "\t broadcast en decimale  \t" << dir_bcast_addr << endl;
                            
                            		 IPAddr.S_un.S_addr = dir_bcast_addr;
                            
                            		  cout << "\t broadcast en IVP4  \t\t" << inet_ntoa(IPAddr) << endl;
                            		
                                    printf("\n");
                            
                                }
                             
                                // Clean up/reset
                                if (pIPAddrTable)
                                {
                                    FREE(pIPAddrTable);
                                    pIPAddrTable = NULL;
                                }
                             
                                return (dir_bcast_addr);
                            }
                            
                            
                            
                            int  main()
                            {
                            	give_the_broadcast();
                            	
                            }
                             
                            
                            
                            0