Walidacja adresu IP

0

Witam wszystkich

Otóż zna ktoś dobrą metodę sprawdzenia poprawności wpisanego przez usera w pole tekstowe aplikacji adresu IP przed zapisem do bazy danych??
Obecnie kombinuje z maska wprowadzania i o tyle w momencie gdy wpisuje się powiedzmy adres IP zgodny z maską XXX.XXX.XXX.XXX czyli np 192.168.100.100 wszystko jest oki, jednak w momencie gdy np adres IP będzie miał postać 192.168.0.1 niestety zgodnie z zadeklarowaną maska dres jest niepoprawny, szukałem trochę w sieci i znalazłem nadklasę realizująca maske dynamiczną ale nie działa w pełni tzn pozwala na wprowadzenie np 192.168.100.10 itp ale nie przyjmuje np 10.10.1.1 :(

class DynamicznyMaskFormatter extends MaskFormatter 
{
    
    public DynamicznyMaskFormatter() 
    {
        super();
    }
 
  
    public DynamicznyMaskFormatter(String mask) 
    throws ParseException 
    {
        super( mask );
    }
 
   
    public Object stringToValue( String value ) 
    throws ParseException 
    {
        Object rv;
 
        String mask = getMask();
        //System.out.println(mask);
        if ( mask != null ) 
        {
          
            setMask( getMaskForString( mask, value ) );
 
            
            rv = super.stringToValue( value.substring( 0, getMask().length() ) );
    
           
            setMask( mask );
        } 
        else
            rv = super.stringToValue( value );
        
        return rv;
    }
 
   
    protected String getMaskForString(String mask, String value) 
    {
    
    	
    	StringBuffer sb = new StringBuffer();
        StringBuffer sb2 = new StringBuffer();
        StringBuffer newMask = new StringBuffer();
        int maskLength = mask.length();
        char placeHolder = getPlaceholderCharacter();
 
        for (int k = 0, size = value.length(); k < size && k < maskLength; k++) 
		        {
		            if (placeHolder == value.charAt(k)) 
		            {
		               break;
		            }
		            sb.append(mask.charAt(k));
		            
		            if (value.charAt(k) == '.') 
		            {
		                for (int i = 0; i < sb2.length(); i++) 
		                {
		                    newMask.append("#");
		                }
		                newMask.append(".");
		                sb2 = new StringBuffer();
		            }
		            else {
		                sb2.append(value.charAt(k));
		            }
		        }
        
        // add on the last octet
        for (int i = 0; i < sb2.length(); i++) 
        {
            newMask.append("#");
        }
 
        //return sb.toString();
        return newMask.toString();
    }

}

Byłbym wdzięczny za pomoc w tym temacie, jestem początkujący i nie wiem jak mogłaby wyglądac inna metoda realizująca to :-(

0

Zawsze można trochę pokombinować np:

public class IPField extends JPanel implements KeyListener {
	private JLabel dot1 = new JLabel(".");
	private JLabel dot2 = new JLabel(".");
	private JLabel dot3 = new JLabel(".");
	
	private JFormattedTextField ip1;
	private JFormattedTextField ip2;
	private JFormattedTextField ip3;
	private JFormattedTextField ip4;
	
	
	public IPField() throws ParseException {
		this.setBackground(Color.WHITE);
		this.setLayout(null);
		this.setBorder(BorderFactory.createLineBorder(Color.BLACK,1));
		init();
		this.add(ip1);
		this.add(ip2);
		this.add(ip3);
		this.add(ip4);
		this.add(dot1);
		this.add(dot2);
		this.add(dot3);
		
		Point p = new Point(2,2);
		ip1.setBounds(p.x, p.y, 30, 20);
		p = new Point(p.x+30,p.y);
		dot1.setBounds(p.x, p.y, 5, 20);
		p = new Point(p.x+5,p.y);
		ip2.setBounds(p.x, p.y, 30, 20);
		p = new Point(p.x+30,p.y);
		dot2.setBounds(p.x, p.y, 5, 20);
		p = new Point(p.x+5,p.y);
		ip3.setBounds(p.x, p.y, 30, 20);
		p = new Point(p.x+30,p.y);
		dot3.setBounds(p.x, p.y, 5, 20);
		p = new Point(p.x+5,p.y);
		ip4.setBounds(p.x, p.y, 30, 20);
	}
	private void init() throws ParseException {
		MaskFormatter format = new MaskFormatter("###");
		
		ip1 = new JFormattedTextField(format);
		ip1.setBorder(null);
		ip1.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
		ip1.addKeyListener(this);
		
		ip2 = new JFormattedTextField(format);
		ip2.setBorder(null);
		ip2.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
		ip2.addKeyListener(this);
		
		ip3 = new JFormattedTextField(format);
		ip3.setBorder(null);
		ip3.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
		ip3.addKeyListener(this);
		
		ip4 = new JFormattedTextField(format);
		ip4.setBorder(null);
		ip4.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
		ip4.addKeyListener(this);
	}
	
	public String getText() {
		return ip1.getText().trim()+"."+ip2.getText().trim()+"."+ip3.getText().trim()+"."+ip4.getText().trim();
	}
	
	public Dimension getPreferredSize() {
		return new Dimension(140, 25);
	}
	
	public void keyPressed(KeyEvent e) {
		if(!(e.getSource() instanceof JFormattedTextField)) return;
		if(e.getSource().equals(ip1)) {
			int length = ip1.getText().trim().length();
			if(length >=2) {
				ip1.setFocusable(false);
				ip2.setFocusable(true);
				ip1.setFocusable(true);
			} 
		} else if(e.getSource().equals(ip2)) {
			int length = ip2.getText().trim().length();
			if(length >=2) {
				ip2.setFocusable(false);
				ip3.setFocusable(true);
				ip2.setFocusable(true);
			} 
		} else if(e.getSource().equals(ip3)) {
			int length = ip3.getText().trim().length();
			if(length >=2) {
				ip3.setFocusable(false);
				ip4.setFocusable(true);
				ip3.setFocusable(true);
			} 
		}
	}
 	public void keyReleased(KeyEvent e) {
 	}
 	public void keyTyped(KeyEvent e) {
 	}
}
0
public static boolean validate(String in){
		String regex = "^([0-9]{1}|[0-9]{2}|[0-9]{3})\\.([0-9]{1}|[0-9]{2}|[0-9]{3})\\.([0-9]{1}|[0-9]{2}|[0-9]{3})\\.([0-9]{1}|[0-9]{2}|[0-9]{3})$";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(in);
		return m.matches();
	}

A może coś takiego :-)

0

Maska w tym przypadku nie jest najlepszym rozwiązaniem, bo adres IP może być zapisany w różny sposób. Lepszym rozwiązaniem, choć nie polecanym, jest użycie wyrażenia regularnego:
\b(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]?)\b
<font size="2">źródło: http://www.regular-expressions.info/examples.html</span>

trzecim i chyba najlepszym rozwiązaniem, i tu ciekawostka rzadko kiedy stosowanym, jest wykorzystanie funkcji split():

public class App {
    public static void main( String[] args ) {
        App a = new App();

        System.out.println( a.validateIp( "256.12.12.123" ) );
    }

    boolean validateIp( String ip ) {
        String[] ipElems = ip.split( "\\." );
        for ( String s : ipElems ) {
            if ( Integer.parseInt( s ) > 255 ) {
                return false;
            }
        }
        return true;
    }
}

jest to bardzo lekkie rozwiązanie, jednak nie pozbawione wad. Trzeba samemu napisać i dokładnie przetestować, a to nie fajne jest.

0

A może tak ?

 try
{
     InetAddress ia=InetAddress.getByName(txt);
}
catch(Exception e)
{
     System.out.println("Podany adres jest niepoprawny");
}

pozdrawiam

0

@bogdans, sterowanie za pomocą wyjątków jest dobre w C++ nie w Javie. Tu strasznie będzie mulić.
@kaziuuu, ten regexp łyknie też IP Radia Mari: 666.666.666.666

0

@Koziołek, wiem ale nie miałem czasu robić pełnej walidacji :-D Koziołek przykład twój połknie np: 22.22, 22.1.1.1.1.1.1, a rzuci błędem przy aa.1.1.1. Przykład pozbawiony wad przykładu @Koziołka:

public static boolean validate(String in){
		StringTokenizer st=new StringTokenizer(in,".");
		boolean pom=true;
		int i;
		int liczba=0;
		for(i=0;st.hasMoreTokens();i++){
			try{
				liczba=Integer.parseInt(st.nextToken());
			}catch(NumberFormatException e){
				pom=false;
				break;
			}
			if(liczba>255||liczba<0){
				pom=false;
				break;
			}
		}
		if(pom&&i==4){
			return true;
		}else{
			return false;
		}
	}
0

A tu dla C#, dokleiłem bo tam nie znalazłem takiego wątku.
pozdr.

public static bool ValidateIP(string addressIP)
{
int val = 0;
string[]tab = addressIP.Split('.');
if (tab.Length != 4) return false;

  foreach (string s in tab)
  {
    bool ok = int.TryParse(s, out val);
    if (!ok) return false;
    if (val > 255 || val < 0) return false;
  }
  return true;
}
0

C# ;)

    public static bool ValidateIP(string addressIP)
    {
      int val = 0;
      string[]tab = addressIP.Split('.');
      if (tab.Length != 4) return false;

      foreach (string s in tab)
      {
        bool ok = int.TryParse(s, out val);
        if (!ok) return false;
        if (val > 255 || val < 0) return false;
      }
      return true;
    }

1 użytkowników online, w tym zalogowanych: 0, gości: 1