首页 > 试题广场 >

判断ip地址是否合法

[编程题]判断ip地址是否合法
  • 热度指数:980 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解


某网络系统需要对输入的IP地址进行合法性判断。IP地址由四个十进制数字组成,每个数字的取值范围是0到255(包含0和255)。
IP地址的格式为X.X.X.X,其中X表示一个十进制数字。系统要求判断输入的IP地址是否合法,即满足以下条件:


1.IP地址由四个数字组成,用点号分隔。

2.每个数字的取值范围是0到255。

3.数字之间没有多余的前导零,例如01是非法的。

4.IP地址不能以点号开始或结束,例如.192.168.0.1和192.168.0.1.是非法的。

不合法的情况下输出"invalid",合法的情况下,你还需要判断是哪一类地址:

A类地址:地址范围从1.0.0.0到126.0.0.0

B类地址:地址范围从128.0.0.0到191.255.255.255

C类地址:范围从192.0.0.0到223.255.255.255
其它地址:合法输入,但是不是A、B、C类
请通过代码实现上述功能


输入描述:
一行字符串,表示需要判断的IP地址


输出描述:
不合法的情况下,输出“invalid”
A类地址,输出“A_address"
B类地址,输出“B_address"
C类地址,输出“C_address"
其它地址,输出“other”
示例1

输入

1.2.3.4

输出

A_address
示例2

输入

1.1.1.256a

输出

invalid
示例3

输入

192.168.0.1

输出

C_address
// 链接:https://www.nowcoder.com/questionTerminal/251319ca3ac1419390c74b540aa72ed5?page=1&onlyReference=false
// 来源:牛客网

#include <bits/stdc++.h>
using namespace std;

int main(int argc, char const *argv[])
{
    string s;
    cin >> s;
    string s_copy = s;
    int k = 0;
    int count = 0;
    for (size_t i = 0; i < s.size(); i++)
    {
        if (s[i] == '.')
        {
            s[i] = '\0';
            if ((s[k] == '0' && strlen(&s[k]) > 1) || strlen(&s[k]) < 1 || atoi(&s[k]) > 255)
            {
                // return false;
                cout << "invalid" << endl;
                return 0;
            }
            k = i + 1;
            count++;
        }
        else
        {
            if (s[i] < '0' || s[i] > '9')
            { // return false;
                cout << "invalid" << endl;
                return 0;
            }
        }
    }
    if (count != 3)
    {
        cout << "invalid" << endl;
        return 0;
    }

    // cout << s << endl;
    int a, b, c, d;
    sscanf(s_copy.c_str(), "%d.%d.%d.%d", &a, &b, &c, &d);
    if ((a >= 1 && a < 125 && b >= 0 && b <= 255 && c >= 0 && c <= 255 && d >= 0 && d <= 255) || (a == 126 && b == 0 && c == 0 && d == 0))
    {
        cout << "A_address" << endl;
    }
    else if (a >= 128 && a <= 191 && b <= 255 && c >= 0 && c <= 255 && d >= 0 && d <= 255)
    {
        cout << "B_address" << endl;
    }
    else if (a >= 192 && a <= 223 && b <= 255 && c >= 0 && c <= 255 && d >= 0 && d <= 255)
    {
        cout << "C_address" << endl;
    }
    else
    {
        cout << "other" << endl;
    }
    return 0;
}

发表于 2024-03-20 22:37:07 回复(0)
try:
    s = input()
    if s[0] == '.' or s[-1] == '.':
        print('invalid')
    else:
        a, b, c, d = s.split('.')
        if (len(a) != 1 and a[0] == '0') or (len(b) != 1 and b[0] == '0') or (len(c) != 1 and c[0] == '0') or (len(d) != 1 and d[0] == '0'):
            print('invalid')
        else:
            a, b, c, d = int(a), int(b), int(c), int(d)
            if 0 <= a <= 255 and 0 <= b <= 255 and 0 <= c <= 255 and 0 <= d <= 255:
                if 1 <= a <= 125 or (a == 126 and b == 0 and c == 0 and d == 0):
                    print('A_address')
                elif 128 <= a <= 191:
                    print('B_address')
                elif 192 <= a <= 223:
                    print('C_address')
                else:
                    print('other')
            else:
                print('invalid')
except:
    print('invalid')
发表于 2023-09-12 23:52:23 回复(0)
import re

s = input()
pattern = r'^(25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d?|0)\.(25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d?|0)\.(25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d?|0)\.(25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d?|0)$'


match = re.match(pattern,s)
if match:
a = int(match.group(1))
b = int(match.group(2))
c = int(match.group(3))
d = int(match.group(4))
# print(a,b,c,d)
if (a<=125 and a>=1) or (a==126 and b==0 and c==0 and d==0): #error:a>=1
print('A_address')
elif a>=128 and a<=191:
print('B_address')
elif a<=223 and a>=192:
print('C_address')
else :
print('other')
else:
print('invalid')
发表于 2024-03-10 00:17:04 回复(0)
java 判断较多,谁看看还有没有优化的空间
package day13; import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) {
        Scanner scanner = new Scanner(
                System.in); // 创建Scanner对象并传入标准输入流(键盘)作为参数  String addStr = scanner.nextLine();  if (addStr.equals("") || addStr == null) {
            System.out.println("invalid");  return;  } //String addStr = "195.25.3.4";  char c1 = addStr.charAt(0);  char c2 = addStr.charAt(addStr.length() - 1);  String s1 = Character.toString(c1);  String s2 = Character.toString(c2);  String[] strings = new String[]{ "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"  };  int temp = 0;  for (String string : strings) { if (string.equals(s1)) {
                temp++;  } if (string.equals(s2)) {
                temp++;  }
        } if (temp != 2) {
            System.out.println("invalid");  return;  }
        String[] split = addStr.split("\\.");  if (split.length != 4) {
            System.out.println("invalid");  return;  } for (String s : split) { if (s.length() == 2 && Character.toString(s.charAt(0)).equals("0")) {
                System.out.println("invalid");  return;  }
        } for (int i = 0; i < split.length; i++) { try { if (Integer.parseInt(split[i]) > 255) {
                    System.out.println("invalid");  return;  }
            } catch (NumberFormatException e) {
                System.out.println("invalid");  return;  }
        } int address1 = Integer.parseInt(split[0]);  int address2 = Integer.parseInt(split[1]);  int address3 = Integer.parseInt(split[2]);  int address4 = Integer.parseInt(split[3]);  if (address1 < 126 && address1 > 0 || address1 == 126 && address2 == 0 && address3 == 0 && address4 == 0) {
            System.out.println("A_address");  } else if (address1 >= 128 && address1 <= 191) {
            System.out.println("B_address");  } else if (address1 >= 192 && address1 <= 223) {
            System.out.println("C_address");  } else {
            System.out.println("other");  }
    }
}

发表于 2024-01-14 00:16:41 回复(0)
#include <bits/stdc++.h>
using namespace std;
#define IO ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
typedef long long ll;
const long long mod=1e9+7;
int n,m;
bool checkV4(string s){
    int k=0;        //记录每个segment起始位置
    int pCnt=0;     //记录'.'的个数
    s.push_back('.');   //方便atoi使用
    for(int i=0; i<s.size(); ++i){
        if(s[i] == '.'){
            s[i] = '\0';    //方便atoi使用
            if( s[k]=='\0'                                //连续..或第一个为.的情况
                || (s[k]=='0' && strlen(&s[k])>1)         //以0开头的情况
                || !(atoi(&s[k])<=255 && atoi(&s[k])>=0)) //不符合区间范围
            {
                return false;
            }
            k = i+1;
            ++pCnt;
        } else if(!(s[i]>='0' && s[i]<='9')) {            //包含非 0-9或'.' 的情况
            return false;
        }
    }
    
    if(pCnt != 3+1) return false;     //'.'不是3段,最后一个1是自己加的
    
    return true;
}
void solve()
{
    string s;
    cin>>s;
    if(!checkV4(s))
    {
        cout<<"invalid"<<"\n";
        return ;
    }
    int a,b,c,d;
    sscanf(s.c_str(),"%d.%d.%d.%d",&a,&b,&c,&d);
    
    if((1<=a&&a<=125&&0<=b&&b<=255&&0<=c&&c<=255&&0<=d&&d<=255)||(a==126&&b+c+d==0))
    {
        cout<<"A_address"<<"\n";
    }else if((128<=a&&a<=191&&0<=b&&b<=255&&0<=c&&c<=255&&0<=d&&d<=255))
    {
        cout<<"B_address"<<"\n";
    }else if((192<=a&&a<=223&&0<=b&&b<=255&&0<=c&&c<=255&&0<=d&&d<=255))
    {
        cout<<"C_address"<<"\n";
    }else 
    {
        cout<<"other"<<"\n";
    }
}
int main()
{
    IO;
    int tn=1;
    solve();
    return 0;
}
发表于 2023-10-16 17:06:25 回复(0)
发表于 2023-09-07 18:41:33 回复(0)
ip = input()
if ip[0] == '.'&nbs***bsp;ip[-1] == '.':
    print('invalid')
else:
    flag = True
    for i in range(len(ip)):
        if ip[i] != '.' and (ip[i]< '0'&nbs***bsp;ip[i] > '9'):
            flag = False
            print('invalid')
            break
        elif ip[i] == '.':
            if ip[i+1] == '.':
                flag = False
                print('invalid')
                break
    if flag:
        iplist = ip.split('.')
        if len(iplist) != 4:
            print('invalid')
        else:
            flag = True
            for j in iplist:
                if j[0] == '0' and len(j) > 1:
                    flag = False
                    print('invalid')
                    break
                elif int(j) < 0&nbs***bsp;int(j) > 255:
                    flag = False
                    print('invalid')
                    break
            if flag:
                iplist = [int(i) for i in iplist]
                if (iplist[0] >= 1 and iplist[0] < 126)&nbs***bsp;\
                (iplist[0] == 126 and iplist[1] == 0 and iplist[2] == 0 and iplist[3] == 0):
                    print('A_address')
                elif iplist[0] >= 128 and iplist[0] < 192:
                    print('B_address')
                elif iplist[0] >= 192 and iplist[0] < 224:
                    print('C_address')
                else:
                    print('other')

发表于 2023-08-31 11:42:40 回复(0)