如何验证IP地址是否正确?

时间:2016-06-20 16:20:27

标签: javascript ip

我正在创建snmp会话一切都按预期工作,我将获得host的动态值来创建会话,我只想把if条件检查ip地址是否正确,有没有办法在javascript中验证IP地址?

main.js

var host = "135.01.01.01";
var sessionOptions = {
    port: 161,
    retries: 1,
    timeout: 5000,
    transport: "udp4",
    trapPort: msg.event.body.trapPort,
    version: snmpVersion
};
//Create snmp Session
var session = snmp.createSession(host, "public", sessionOptions);

try {
    if (!host) {
        console.log("Could not find host");
    } else {
        session.trap(trapOid, varbinds, options, function(error) {
            if (error)
                console.log(error);
            else
                console.log('SNMP successfully delivered');
        });
    }
} catch (e) {
    console.log("SNMP processing error: " + e);
}

1 个答案:

答案 0 :(得分:1)

改编自here

function ValidateIPaddress(ipaddress)   
{  
 if (/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(host))  
  {  
    return (true)  
  }  
return (false)  
}