본문 바로가기

JAVA

자바채팅 프로그래밍 - 호스트 정보 알기

 

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;

public class GetHostInfor extends Frame implements ActionListener {
	
	TextField hostname,hostclass;
	Button getinfor;
	TextArea display;
	public static void main(String args[]){	
	GetHostInfor host = new GetHostInfor("InetAddress 클래스");
	host.setVisible(true);
	}
	public GetHostInfor(String str) {
		super(str);
		addWindowListener(new WinListener());
		setLayout(new BorderLayout());
		
		Panel inputpanel = new Panel();
		inputpanel.setLayout(new BorderLayout());
		inputpanel.add("North",new Label("호스트 이름"));
		hostname = new TextField("",30);
		getinfor = new Button("호스트 정보 얻기");
		inputpanel.add("Center",hostname);
		inputpanel.add("South",getinfor);
		getinfor.addActionListener(this);
		add("North",inputpanel);
		
		Panel outputpanel = new Panel();
		outputpanel.setLayout(new BorderLayout());
		display = new TextArea("",24,40);
		display.setEditable(false);
		outputpanel.add("North",new Label("인터넷 주소"));
		outputpanel.add("Center",display);
		add("Center",outputpanel);
		
		Panel panel3 = new Panel();
		panel3.setLayout(new BorderLayout());
		panel3.add("North",new Label("대표IP주소 클래스 유형"));
		hostclass = new TextField("",50);
		panel3.add("Center",hostclass);
		add("South",panel3);
		setSize(300,300);
	}

	static char ipClass(byte[] ip) {
		int highByte = 0xff & ip[0];
		return(highByte < 128) ? 'A' : (highByte < 192) ? 'B' : (highByte < 224) ? 'C' : (highByte < 240) ? 'D' : 'E';
	}
	class WinListener extends WindowAdapter{
		public void windowClosing(WindowEvent we) {
			System.exit(0);
		}
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		String name = hostname.getText();
		try {
			InetAddress inet = InetAddress.getByName(name);
			String ip = inet.getHostName() +"\n";
			display.append(ip);
			ip = inet.getHostAddress() +"\n";
			display.append(ip);
			//입력된 호스트에 할당된 모든주소
			InetAddress[] inet2 = InetAddress.getAllByName(hostname.getText());
			display.append("모든 호스트 주소" +"\n");
			for(int i=0; i<inet2.length; i++) {
				display.append(inet2[i].toString() + "\n");
			}
			//대표 IP주소 클래스유형 구하기
			char whatclass = ipClass(inet.getAddress());
			String change = "";
			change = Character.toString(whatclass);
			hostclass.setText(change);

		}catch(UnknownHostException ue) {
			String ip = name + "해당 호스트가 없습니다.\n";
			display.append(ip);
		}
		
	}
}

 

<결과>