ip地址转换

bool IP2Num(const char* ip,struct in_addr& addr)
{
    for(int i=0;i<strlen(ip);++i)
    {
        if('.'==ip[i])continue;
        if('0'<=ip[i]&&'9'>=ip[i])continue;
        return false;
    }

    int ch[4]={0};
    if(4!=sscanf(ip,"%d.%d.%d.%d",&ch[0],&ch[1],&ch[2],&ch[3]))return false;
    addr.S_un.S_addr=0;

    addr.S_un.S_addr+=(ch[3]&0xff);
    addr.S_un.S_addr=addr.S_un.S_addr<<8;

    addr.S_un.S_addr+=(ch[2]&0xff);
    addr.S_un.S_addr=addr.S_un.S_addr<<8;

    addr.S_un.S_addr+=(ch[1]&0xff);
    addr.S_un.S_addr=addr.S_un.S_addr<<8;

    addr.S_un.S_addr+=(ch[0]&0xff);
    return true;
}

 

posted on 2018-12-05 22:26  弘道者  阅读(254)  评论(0编辑  收藏  举报