addr/addr_from_str.c

Go to the documentation of this file.
00001 // Copyright (C) 2006-2007 Benedikt Böhm <hollow@gentoo.org>
00002 //
00003 // This program is free software; you can redistribute it and/or
00004 // modify it under the terms of the GNU General Public License
00005 // as published by the Free Software Foundation; either version 2
00006 // of the License, or (at your option) any later version.
00007 //
00008 // This program is distributed in the hope that it will be useful,
00009 // but WITHOUT ANY WARRANTY; without even the implied warranty of
00010 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00011 // GNU General Public License for more details.
00012 //
00013 // You should have received a copy of the GNU General Public License
00014 // along with this program; if not, write to the Free Software
00015 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
00016 
00017 #include "addr.h"
00018 #include "scanf.h"
00019 #include "str.h"
00020 
00021 int addr_from_str(const char *str, uint32_t *ip, uint32_t *mask)
00022 {
00023         int rc = 0;
00024         int cidr;
00025 
00026         union {
00027                 uint8_t  b[4];
00028                 uint32_t l;
00029         } u;
00030 
00031         const char *p = str_chr(str, '/', str_len(str));
00032 
00033         /* ip address */
00034         if (!p || p - str > 0) {
00035                 if (_lucid_sscanf(str, "%hhu.%hhu.%hhu.%hhu",
00036                                         &u.b[0], &u.b[1], &u.b[2], &u.b[3]) == 4) {
00037                         if (ip)
00038                                 *ip = u.l;
00039 
00040                         rc = 1;
00041                 }
00042         }
00043 
00044         if (!p)
00045                 return rc;
00046 
00047         p++;
00048 
00049         /* netmask in CIDR notation */
00050         if (!str_isempty(p) && str_isdigit(p)) {
00051                 if (_lucid_sscanf(p, "%d", &cidr) == 1 && (cidr > 0 && cidr <= 32)) {
00052                         if (mask)
00053                                 *mask = addr_hton(0xffffffff & ~((1 << (32 - cidr)) - 1));
00054 
00055                         rc   += 2;
00056                 }
00057         }
00058 
00059         /* netmask in ip notation */
00060         if (!str_isempty(p)) {
00061                 if (_lucid_sscanf(p, "%hhu.%hhu.%hhu.%hhu",
00062                                         &u.b[0], &u.b[1], &u.b[2], &u.b[3]) == 4) {
00063                         if (mask)
00064                                 *mask = u.l;
00065 
00066                         rc += 2;
00067                 }
00068         }
00069 
00070         return rc;
00071 }

Generated on Tue Jun 19 20:38:25 2007 for lucid by  doxygen 1.5.2