Obtaining ip addresses of all devices in the network through UDP broadcasting

Explain:

Source download address: http://download.csdn.net/detail/dxzysk/9756896

Source code usage instructions, first run server-side program on the host that needs to get IP address, and then run client-side program on Pc that needs to search for host.

This paper is a windows version, VC++, debugged successfully in VS2010 environment. Sometimes it is necessary to search for devices, machines, servers, etc. in the network. This requires UDP broadcasting to send broadcast commands to every host in the network. When the host or device receives the broadcast commands, it immediately sends its own device information to the requester. Here is an example of IP information.

thinking

In each device, sever program is deployed to monitor. Client sends broadcast commands. After receiving commands, each server returns the information of its own ip address to client. The code is as follows. Some of them, such as getting ip address reference from the network, respecting the originality, are happy to share.

server side (windows console program)

The server listens for the broadcast command "GetIPAddr", and when it receives the command, it responds accordingly.

#include <WinSock2.h>  
#include <stdio.h>  
#include <iostream>   
using namespace std;  

#pragma comment(lib, "ws2_32.lib")   

#define GET_HOST_COMMAND "GetIPAddr"
const int MAX_BUF_LEN = 255;
#define SERVER_PORT 12811   

//Return only one ip address
bool GetLocalIP(char* ip)  
{  
    //1. Initialization of wsa  
    WSADATA wsaData;  
    int ret=WSAStartup(MAKEWORD(2,2),&wsaData);  
    if (ret!=0)  
    {  
        return false;  
    }  
    //2. Get the host name  
    char hostname[256];  
    ret=gethostname(hostname,sizeof(hostname));  
    if (ret==SOCKET_ERROR)  
    {  
        return false;  
    }  
    //3. Get the host ip  
    HOSTENT* host=gethostbyname(hostname);  
    if (host==NULL)  
    {  
        return false;  
    }  
    //4. Convert to char* and copy back  
    strcpy(ip,inet_ntoa(*(in_addr*)*host->h_addr_list));  
    return true;  
} 

bool doServer(){
    int m_nPort = SERVER_PORT;

    SOCKET sClient;
    sockaddr_in clientAddr,bindAddr;
    WSADATA wsdata;

    //Start the SOCKET library, version 2.0
    WORD    wVer=MAKEWORD(2,0);
    if( 0 != WSAStartup(wVer,&wsdata) )
    {
        //AfxMessageBox(L"Not Support Socket2.0");
        return false;
    }

    //Initialization of sockets with UDP
    sClient=socket(AF_INET,SOCK_DGRAM,0);
    //Set the socket to the broadcast type.
    BOOL optval=TRUE;
    bindAddr.sin_family=AF_INET;
    bindAddr.sin_addr.s_addr=htonl(INADDR_ANY);
    bindAddr.sin_port=htons(m_nPort);
    setsockopt(sClient,SOL_SOCKET,SO_BROADCAST,(char FAR *)&optval,sizeof(optval));
    bind(sClient,(sockaddr *)&bindAddr,sizeof(sockaddr_in));

    int nAddrLen = sizeof(SOCKADDR);   
    char buf[256] = {0};
    int fromlength=sizeof(SOCKADDR);
    printf("the server is start.\n");

    char ipaddr[30] = {0};

    char buff[MAX_BUF_LEN] = ""; 
    if (GetLocalIP(ipaddr))
    {
        sprintf(buff, "my ip is:%s", ipaddr);   
    }
    else
    {
        sprintf(buff, "%s", "my ip is:******"); 
    }

    //When there are multiple ip addresses, call this
    //IPInfo ips[10];
    //int len1 = 0;
    //GetLocalIPs(ips, 10,&len1);

    while(true)
    {
        int nRet = recvfrom(sClient,buf,256,0,(struct sockaddr FAR *)&clientAddr,(int FAR *)&fromlength);
        if( SOCKET_ERROR != nRet )
        {
            char    *pIPAddr = inet_ntoa(clientAddr.sin_addr);
            if( NULL != pIPAddr )
            {
                WCHAR    wzIPBuffer[32] = {0};
                printf("clientAddr: %s\n", pIPAddr);
                printf("receive command: %s\n", buf);
            }
            if (strcmp(buf,GET_HOST_COMMAND) != 0)
            {
                printf("the command not valid and was ignored.\n", buf);
                continue;
            }
            // send data   
            int nSendSize = sendto(sClient, buff, strlen(buff), 0, (SOCKADDR*)&clientAddr, nAddrLen);   
            if(SOCKET_ERROR == nSendSize)   
            {   
                int err = WSAGetLastError();   
                printf("\"sendto\" error!, error code is %d\n", err);   
                return false;   
            }

        }
        else
        {
            //AfxMessageBox(L"Recv UDP Failed");
        }

        Sleep(1000);
    }

    closesocket(sClient);
    return true;
}

int main()
{
    if (!doServer())
    {
        printf("sever returned an error");
        return -1;
    }
    return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136

Note that there is only one IP address above. Some machines may have multiple IP addresses, different networks, wired networks, wireless wifi, etc. It is necessary to obtain multiple IP addresses.

//Structures record ip information
typedef struct tagIPInfo  
{  
    char ip[30];  
}IPInfo;  

//Get multiple lists of ip address information
bool GetLocalIPs(IPInfo* ips,int maxCnt,int* cnt)  
{  
    //1. Initialization of wsa  
    WSADATA wsaData;  
    int ret=WSAStartup(MAKEWORD(2,2),&wsaData);  
    if (ret!=0)  
    {  
        return false;  
    }  
    //2. Get the host name  
    char hostname[256];  
    ret=gethostname(hostname,sizeof(hostname));  
    if (ret==SOCKET_ERROR)  
    {  
        return false;  
    }  
    //3. Get the host ip  
    HOSTENT* host=gethostbyname(hostname);  
    if (host==NULL)  
    {  
        return false;  
    }  
    //4. Convert to char * one by one and copy it back  
    *cnt=host->h_length<maxCnt?host->h_length:maxCnt;  
    for (int i=0;i<*cnt;i++)  
    {  
        in_addr* addr=(in_addr*)*host->h_addr_list;  
        strcpy(ips[i].ip,inet_ntoa(addr[i]));  
    }  
    return true;  
} 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38

client side (windows console program)

Client sends "GetIPAddr" command and receives information from client in time

//#include "stdafx.h"  
#include <WinSock2.h>  
#include <stdio.h>  

#pragma comment(lib, "ws2_32.lib")   

const int MAX_BUF_LEN = 255;   

#define GET_HOST_COMMAND "GetIPAddr"
#define CLIENT_PORT 11121
#define SERVER_PORT 12811

int main()   
{   
    int nPort = SERVER_PORT;
    WORD wVersionRequested;   
    WSADATA wsaData;   
    int err;   

    // Start socket api   
    wVersionRequested = MAKEWORD( 2, 2 );   
    err = WSAStartup( wVersionRequested, &wsaData );   
    if ( err != 0 )   
    {   
        return -1;   
    }   

    if ( LOBYTE( wsaData.wVersion ) != 2 || HIBYTE( wsaData.wVersion ) != 2 )   
    {   
            WSACleanup( );   
            return -1;    
    }   

    // Create socket   
    SOCKET connect_socket;   
    connect_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);   
    if(INVALID_SOCKET == connect_socket)   
    {   
        err = WSAGetLastError();   
        printf("\"socket\" error! error code is %d\n", err);   
        return -1;   
    }   

    // Used to bind sockets   
    SOCKADDR_IN sin;   
    sin.sin_family = AF_INET;   
    sin.sin_port = htons(CLIENT_PORT);   
    sin.sin_addr.s_addr = 0;   

    // Used to receive data from broadcast addresses on the network   
    SOCKADDR_IN sin_from;   
    sin_from.sin_family = AF_INET;   
    sin_from.sin_port = htons(nPort);   
    sin_from.sin_addr.s_addr = INADDR_BROADCAST;   

    //Set the socket to the broadcast type.   
    bool bOpt = true;   
    setsockopt(connect_socket, SOL_SOCKET, SO_BROADCAST, (char*)&bOpt, sizeof(bOpt));   

    // Binding sockets   
    err = bind(connect_socket, (SOCKADDR*)&sin, sizeof(SOCKADDR));   
    if(SOCKET_ERROR == err)   
    {
        err = WSAGetLastError();   
        printf("\"bind\" error! error code is %d\n", err);   
        return -1;   
    }   

    printf("the client is start.\n");
    int nAddrLen = sizeof(SOCKADDR);   
    char buff[MAX_BUF_LEN] = "";   
    int nLoop = 0;  

    char    szMsg[]=GET_HOST_COMMAND;
    int nLen=sizeof(sin_from);
    if( SOCKET_ERROR==sendto(connect_socket, szMsg, strlen(szMsg), 0, (sockaddr*)&sin_from, nLen) )
    {
       // AfxMessageBox(L"Send UDP Failed");  
        return -1;
    }

    printf("send broadcast data:%s\n", GET_HOST_COMMAND);

    while(true)   
    {   
        // receive data   
        int nSendSize = recvfrom(connect_socket, buff, MAX_BUF_LEN, 0, (SOCKADDR*)&sin_from, &nAddrLen);   
        if(SOCKET_ERROR == nSendSize)   
        {   
            err = WSAGetLastError();   
            printf("\"recvfrom\" error! error code is %d\n", err);   
            return -1;   
        }   
        buff[nSendSize] = '\0';   
        printf("received ip: %s\n", buff);   
    }   

    return 0;   
}  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101

Operation result

  • 1.Server end
  • 2.Client side

    Running results show that the two IP addresses are the same, because both client and server are running on the same machine. If there are more than one server, the client can search for more than one ip, which is limited by the conditions, there is only one.
top 0 step on

Keywords: socket network Windows

Added by jansky on Wed, 29 May 2019 13:08:13 +0300