Execute shell commands in the program to automatically obtain all online IP addresses and open ports in the LAN (Linux)

Source: Internet
Author: User
Tags get ip

Execute shell commands in the program to automatically obtain all online IP addresses and open ports in the LAN (Linux)
Preface

The question is a bit long. It is actually the following: first, let the Shell command be executed in the program, and then pass the execution result to the variable, so that subsequent transactions can be processed, the second is to use the nmap command to obtain all the online IP addresses and open ports in the current LAN, and finally process the nmap results to obtain only the IP addresses and ports.

The powerful functions of Linux Command lines are believed to be known to all users of Linux. A command can be implemented only when you use hundreds or even thousands of lines of code in windows. Therefore, if you use shell commands, it can be said that it is twice the result with half the effort.

To make full use of shell results, it is necessary to obtain the result returned by the command that can be processed.

Execute Shell commands in the program

It mainly uses the following functions:

Function Definition:

#include <stdio.h>

FILE * popen(const char *command , const char *type );
int pclose(FILE *stream);

 

Function Description:

The popen () function creates a pipeline, calls fork () to generate a sub-process, and runs a shell to run the command to start a process. This pipeline must be closed by the pclose () function, rather than the fclose () function. The pclose () function closes the standard I/O Stream, waits until the command execution ends, and returns the shell termination status. If the shell cannot be executed, the termination status returned by pclose () is the same as that returned by the shell.

The type parameter can only be read or written. The returned value (standard I/O Stream) also has a read-only or write-only type corresponding to the type. If the type is "r", the file pointer is connected to the standard output of the command; if the type is "w", the file pointer is connected to the standard input of the command.

The command parameter is a pointer to a shell command string ending with NULL. This line of command will be passed to bin/sh and the-c flag will be used, shell will execute this command.

The return value of popen () is a standard I/O Stream and must be terminated by pclose. As mentioned above, this stream is unidirectional (only used for reading or writing ). Writing content to this stream is equivalent to writing standard input to this command. The standard output of the command is the same as the process that calls popen (). In contrast, reading data from a stream is equivalent to reading the standard output of a command. The standard input of a command is the same as the process that calls popen.

Return Value:

If fork () or pipe () fails to be called, or the memory cannot be allocated, NULL is returned. Otherwise, the standard I/O Stream is returned. Popen () does not set errno for memory allocation failure. If an error occurs when fork () or pipe () is called, errno is set to the corresponding error type. If the type parameter is invalid, errno returns EINVAL.

Usage:

//execute shell command
//Execute a shell command, store the output line by line in resvec, and return the number of lines
int32_t myexec(const char *cmd, vector<string> &amp;resvec) {
resvec.clear();
File * PP = Popen (CMD, "R"); / / establish the pipeline
If ((PP) {
Return -1;
}
Char TMP [1024]; / / set an appropriate length to store the output of each line
while (fgets(tmp, sizeof(tmp), pp) != NULL) {
if (tmp[strlen(tmp) - 1] == '\n') {
TMP [strlen (TMP) - 1] = '\ 0'; / / remove line breaks
}
resvec.push_back(tmp);
}
Pclose (PP); / / close the pipeline
return resvec.size();
}
Use nmap to obtain all online IP addresses and open ports

Powerful nmap, detailed introduction to the Internet too much, attached to the official website http://nmap.org/, use the following command

nmap -sT 192.168.1.0/24

Scan the class c cidr block to obtain the result map and format. You can view the format to facilitate subsequent processing of the result:


 

If it is a Class B network segment, change it:

nmap -sT 192.168.*.*/24
Process the result

The main objective of processing is to directly obtain the IP address and the corresponding port number, save it to the vector array, and then facilitate subsequent processing. The processing code is as follows:

int32_t get_ip_port( vector<string> input,map<string,vector<string> > &result)
{
    result.clear();
    vector<string>::iterator it=input.begin();
    int flag=0;
    while(it!=input.end())
    {
        if((*it)[0]!='\0')
        {
            flag++;
            if(flag==1)
            {
                //get IP address and push_back a pair to reslut
                vector<string> tmp;
                const char* IP=new char(24);
                IP=it->data()+21;
                result.insert(pair<string,vector<string> >(IP,tmp));
            }
            else if(flag==2||3)
            {
                //skip
            }
            else
            {
                //get port information
                map<string,vector<string> >::iterator itt=result.end();
                char Port[5];
                const char* p=new char(5);
                p=it->data();
                for(int i=0;i<5;i++)
                {
                    if((*p)!='/')
                    {
                        Port[i]=*p;
                        p++;
                    }
                    else
                        break;
                }
                itt->second.push_back(Port);
            }
            ++it;    
        }
        else
        {
            flag=0;
            ++it;
        }
    }
    return 1;

}

 

Currently, the processing speed is relatively slow. You can see whether the speed can be improved in the future. Although the identification technology of these networks is very useful for system developers, it also gives malicious hackers many opportunities, so it has advantages and disadvantages.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.