Java - 소켓프로그래밍(Socket Programming)

2020. 7. 28. 20:30Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.StringTokenizer;
 
public class Ex {
 
    public static void main(String[] args) {
        /*
         * 소켓프로그래밍(Socket Programming)
         * -소켓(Socket) : 컴퓨터(단말장치) 간에 연결된 끝단(논리적인 개념)
         * 소켓을 서로 연결하여 논리적인 채널을 생성한 뒤, 이 소켓을 통해 데이터를 입출력
         * 
         */
        
        
        
        try {
            //1. InetAddress 클래스
            //자바에서 IP 주소 관련 정보를 관리하는 클래스
            String name="www.itwillbs.co.kr";//도메인 네임
            
            
            //지정된 도메인 네임으로부터 InetAddress 객체 가져오기
            InetAddress inetAddr=InetAddress.getByName(name);
            
            String hostName=inetAddr.getHostName();
            String hostAddress=inetAddr.getHostAddress();
            System.out.println("호스트명 : "+hostName);
            System.out.println("호스트주소 : "+hostAddress);
            
            System.out.println("------------------------------------");
            
            //로컬호스트로부터 InetAddress 객체 가져오기
            //Localhost 란? 현재 자기 자신의 단말장치.
            InetAddress localhost=InetAddress.getLocalHost();
            String localhostName=localhost.getHostName();
            String localhostAddress=localhost.getHostAddress();
            System.out.println("호스트명 : "+localhostName);
            System.out.println("호스트주소 : "+localhostAddress);
        } catch (UnknownHostException e) {
//            e.printStackTrace();
            System.out.println("호스트 주소가 잘못되었습니다."+e.getMessage());
        }
        
        System.out.println("--------------------------------------");
        
        
        try {
            String name="www.amazon.com";//도메인 네임
            
            
            //지정된 도메인 네임으로부터 InetAddress 객체 가져오기
            InetAddress inetAddr=InetAddress.getByName(name);
            
            String hostName=inetAddr.getHostName();
            String hostAddress=inetAddr.getHostAddress();
            System.out.println("호스트명 : "+hostName);
            System.out.println("호스트주소 : "+hostAddress);
            
            /*
             * IP주소 문자열에서 첫번째 옥텟 추출하는 방법
             * 1. String 클래스의 split() 메서드 호출하여 마침표(.)를 기준으로 분리 후
             * 0번 배열값(첫번째 추출숫자) 사용하는 방법(주의! 마침표 "\\."로 지정)
             * 
             */
            
            String firstOctet=hostAddress.split("\\.")[0];
            System.out.println("첫번째 옥텟 : "+firstOctet);
            
            /*
             * 2. StringTokenizer 클래스 사용하는 방법
             * 생성자에 원본문자열(주소)와 구분자(.)를 전달하여 분리 후
             * 첫번째 값을 사용하는 방법
             */
            
            StringTokenizer st=new StringTokenizer(hostAddress,".");
            //별도의 반복문 없이 if문 사용하여 첫번째 토큰을 바로 가져오기
            if(st.hasMoreTokens()) {//다음 토큰 존재 여부 판별
                firstOctet=st.nextToken();
                System.out.println("첫번째 옥텟 : "+firstOctet);
            }
            
            
            
            /*
             * 변수 firstOctet 의 정수 범위에 따라 서브넷마스크를 출력
             * firstOctet 의 정수 문자열을 실제정수로 변환하여 범위 판별 필요
             * 
             * A클래스 :         1~126        255.0.0.0
             * B클래스 :         128~191        255.255.0.0
             * C클래스 :         192~223        255.255.255.0
             */
            
            int firstOctetNum=Integer.parseInt(firstOctet);
            
            if(firstOctetNum>=1&&firstOctetNum<=126) {
                System.out.println(firstOctetNum+ " : A클래스, 서브넷마스크 : 255.0.0.0");
            }else if(firstOctetNum>=128&&firstOctetNum<=191) {
                System.out.println(firstOctetNum+ " : B클래스, 서브넷마스크 : 255.255.0.0");
            }else if(firstOctetNum>=192&&firstOctetNum<=223) {
                System.out.println(firstOctetNum+ " : C클래스, 서브넷마스크 : 255.255.255.0");
            }else {
                System.out.println(firstOctetNum+" : 주소입력오류");
            }
            
        } catch (UnknownHostException e) {
//            e.printStackTrace();
            System.out.println("호스트 주소가 잘못되었습니다."+e.getMessage());
        }
        
        
        
    }
 
}
 
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.regex.Pattern;
 
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
 
public class test extends JFrame {
    private JTextField tfIpAddress;
    private JTextField tfSubnetMask;
    private JTextField tfGateway;
    private JTextField tfDnsServer;
    
    public test() {
        showFrame();
    }
    public void showFrame() {
        setTitle("IP Configuration");
        setBounds(800400500300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        getContentPane().setLayout(null);
        
        
        // -------------DHCP - Static 전환 라디오 버튼---------------
        JRadioButton rbDhcp = new JRadioButton("DHCP");
        rbDhcp.setBounds(302912123);
        getContentPane().add(rbDhcp);
        
        JRadioButton rbStatic = new JRadioButton("Static",true);
        rbStatic.setBounds(306712123);
        getContentPane().add(rbStatic);
        
        //ButtonGroup 객체를 사용하여 라디오버튼 그룹화
        ButtonGroup bg=new ButtonGroup();
        bg.add(rbStatic);
        bg.add(rbDhcp);
        
        //------------라디오 버튼 이벤트 처리= ActionListener------------------------
        //DHCP 선택 시, 텍스트 필드 4개 잠금, 입력 내용 초기화
        //Static 선택 시, 텍스트필드 4개 잠금해제, 입력내용 초기화
        //--------------------------------------------------------------------------
        
        rbStatic.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed(ActionEvent e) {
                tfSubnetMask.setEditable(true);tfSubnetMask.setText("");
                tfIpAddress.setEditable(true);tfIpAddress.setText("");
                tfGateway.setEditable(true);tfGateway.setText("");
                tfDnsServer.setEditable(true);tfDnsServer.setText("");
            }
        });
        
        rbDhcp.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed(ActionEvent e) {
                tfSubnetMask.setEditable(false); tfSubnetMask.setText("");
                tfIpAddress.setEditable(false); tfIpAddress.setText("");
                tfGateway.setEditable(false); tfGateway.setText("");
                tfDnsServer.setEditable(false); tfDnsServer.setText("");
                
            }
        });
        
        //-------------------------------------------------------------
        JLabel lblIpAddress = new JLabel("IP Address");
        lblIpAddress.setBounds(301177315);
        getContentPane().add(lblIpAddress);
        
        JLabel lblSubnet = new JLabel("Subnet Mask");
        lblSubnet.setBounds(301528915);
        getContentPane().add(lblSubnet);
        
        JLabel lblDefaultGateway = new JLabel("Default Gateway");
        lblDefaultGateway.setBounds(3018310515);
        getContentPane().add(lblDefaultGateway);
        
        JLabel lblDnsServer = new JLabel("DNS Server");
        lblDnsServer.setBounds(302217315);
        getContentPane().add(lblDnsServer);
        
        JLabel lbl = new JLabel("");
        lbl.setBounds(1454528734);
        getContentPane().add(lbl);
        
        tfIpAddress = new JTextField();
        tfIpAddress.setBounds(16211427021);
        getContentPane().add(tfIpAddress);
        tfIpAddress.setColumns(10);
        
        tfSubnetMask = new JTextField();
        tfSubnetMask.setBounds(16214927021);
        getContentPane().add(tfSubnetMask);
        tfSubnetMask.setColumns(10);
        
        tfGateway = new JTextField();
        tfGateway.setBounds(16218027021);
        getContentPane().add(tfGateway);
        tfGateway.setColumns(10);
        
        tfDnsServer = new JTextField();
        tfDnsServer.setBounds(16221827021);
        getContentPane().add(tfDnsServer);
        tfDnsServer.setColumns(10);
        
        //-----------------------텍스트필드 이벤트 처리------------------
        
        tfIpAddress.addFocusListener(new FocusListener() {
            
            @Override
            public void focusLost(FocusEvent e) {
//                System.out.println("focuslost");
                //ip 주소 입력란에서 포커스가 벗어날 때 호출되는 메서드
//                String ipAddress=tfIpAddress.getText();
//                System.out.println(ipAddress);
                
                
                //입력된 텍스트가 없을 경우("") 아무것도 하지 않고
                //입력된 텍스트가 있을 경우에만 checkIp() 메서드 호출
                if(!tfIpAddress.getText().equals("")) {
                    boolean checkResult=checkIp(tfIpAddress.getText());
                    
                    //체크결과가 false 일 경우(주소오류) 텍스트필드 초기화 및 포커스 요청
                    if(!checkResult) {
                        tfIpAddress.setText("");
                        tfIpAddress.requestFocus();
                        return;
                    }
                    
                    boolean checkResult2=calculateSubnetMask(tfIpAddress.getText());
                    if(!checkResult2) {
                        tfIpAddress.setText("");
                        tfIpAddress.requestFocus();
                        return;
                    }
                }
            }
            
            @Override
            public void focusGained(FocusEvent e) {
//                System.out.println("focusgained");
            }
        });
        
        
        
        //--------------------------------------------------------------
        
        setVisible(true);
    }
    
    public boolean checkIp(String strIp) {
        System.out.println(strIp);
        
        //정규표현식을 사용하여 IP 주소 형식 체크
        //0.0.0.0 ~ 255.255.255.255 사이만 입력 가능
        String regex="^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$";
        if(!Pattern.matches(regex, strIp)) {
            //주소가 정규표현식에 일치하지 않으면 false 리턴됨
            JOptionPane.showMessageDialog(this"Invalid IP address entered","Error",JOptionPane.ERROR_MESSAGE);
            return false;
        }
        
        //String 클래스의 split() 메서드를 사용하여 주소를 옥텟별로 분리
        String[] ipOctet=strIp.split("\\.");
        for(String s: ipOctet) {
//            System.out.println(s);
            int ipOctetNum=Integer.parseInt(s);
            //정수 범위가 0~ 255 가 아니면 return false
            if(!(ipOctetNum>=0&&ipOctetNum<=255)) {
                JOptionPane.showMessageDialog(this"Invalid IP address entered","Error",JOptionPane.ERROR_MESSAGE);
                return false;
            }
            
        }
        
        
        return true;
    }
    
    public boolean calculateSubnetMask(String strIp) {
        //정상 범위 내의 IP 주소 첫번째 옥텟 범위에 따른 서브넷마스크 계산
        //계산된 서브넷마스크를 텍스트 필드에 표시
        String[] ipOctet=strIp.split("\\.");
        int ipOctetNum=Integer.parseInt(ipOctet[0]);
 
        if(ipOctetNum>=1&&ipOctetNum<=126) {
            tfSubnetMask.setText("255.0.0.0");
        }
        if(ipOctetNum>=128&&ipOctetNum<=191) {
            tfSubnetMask.setText("255.255.0.0");
        }
        if(ipOctetNum>=192&&ipOctetNum<=223) {
            tfSubnetMask.setText("255.255.255.0");
        }
        else {
            JOptionPane.showMessageDialog(this"Invalid IP address entered","Error",JOptionPane.ERROR_MESSAGE);
            return false;
        }
        
        return true;
    }
 
    public static void main(String[] args) {
        new test();
    }
}
 
 
cs

 

ip주소에 대해서 조금 더 배워보았다. ip주소와 Subnet Mask의 주소 값을 활용해서 네트워크 연결이 되는지 알 수 있고

클래스에 따라 서브넷마스크 의 값이 다르다는 것도 알게 되었다.