본문 바로가기

개발기술/Computer Science

CS공부 - 네트워크

네트워크 개요

- 네트워크 : 컴퓨터간의 통신(파일,이메일,웹문서 송수신)을 일컫으며 이 통신에는 합의된 규칙(프로토콜)이 있음

- 네트워크분류 : 커버 범위에 따라서 지역의  LAN(Local Area Network), 무선의 WLAN(Wireless), ISP(인터넷서비스 프로바이더)가 제공하는 광역의 WAN(Wide)이 존재함.

- LAN : 해당 지역의 네트워크를 모두 연결하고 중개하는 허브에 연결하기 위해 각각의 Device에 부착된 LAN 카드를 활용한다.

- WAN : ISP는 해당 지역의 중개허브들을 연결하여 국가 내, 국가 간 케이블을 통해서 데이터를 송수신한다. ISP 외에도 Google같은 사기업이 국가간 케이블을 보유하는 경우도 있음. 해당 부분의 자세한 내용은 네트워크를 전문으로하는 네트워크 엔지니어의 영역이며 프로그래밍과는 다소 괴리가 있음.

- 프로토콜 : 컴퓨터간 통신을 하기위한 규칙이며 택배박스의 택배송장(목적지, 내용물, 분류 등등의 정보)와 유사한 역할을 하며, 한번에 end to end 통신이 아니기때문에 여러가지 프로토콜이 존재함

OSI 7계층

- ISO(국제표준화기구)에서 다양한 컴퓨터간 통신체계에 대해서 표준화 스펙을 제시한 개념, 실제와 완전히 동일하지는 않으나 개념화라는 측면에서 유용

- OSI 7계층의 핵심은 계층화에 있다. 각 전송의 계층마다 역할에 필요한 정보가 있고 그 필요한 정보를 data 앞의 head부문에 부착을 하는 형태이다. 계층별로 header의 capsulation과 decapsulation을 통해 전송을 위한 정보를 교환하고 이에 따라 전송의 행위를 한다. 이때, 이전 계층의 head는 다음 계층에서 통으로 data로 취극하여 계층 간 독립성을 유지한다. 이러한 계층별 독립적 전송방식은, 한 계층의 프로토콜 변화로 인해서 다른 계층도 종속적으로 변경해야하는 경우를 방지한다.

OSI 7계층별 역할

암기법 : A아P파S서T탈N났D다PHY픽

  • 1계층 (물리계층Physical ) : 시스템간 물리적 연결과 전기신호 변환  및 제어 ; 0과1의 데이터를 전기신호로 변환
  • 2계층 (데이터링크 계층 Datalink) : 네트워크 기기 간 데이터 전송 및 물리주소 결정 ; 랜카드마다 고유한 맥주소를 사용하는 이더넷 프로토콜로 랜카드에서 랜카드로 데이터 전송
  • -- 데이터링크 계층까지의 데이터를 프레임, 네트워크 계층부터의 데이터를 패킷이라 칭함.
  •  
  • 3계층 (네트워크 계층 Network) :
    • 다른 네트워크와 통신을 위한 경로 설정 및 논리주소 결정; 광역  WAN 네트워크 내에서의 IP 프로토콜을 활용하여 국가 내, 국가 간 최적의 경로를 관리. The data is divided into packets. 
  • - 4계층 (전송계층 Transport ) : 신뢰할 수 있는 통신 구현; 데이터가 전송중 유실이 있는지 체크섬을 통해서 확인하고 포트를 구분하여 어떤 응용프로그램에 데이터가 전달되어야하는지 구분함. 프로그램별로 일반적으로 많이쓰는 포트번호가 있음 (웹서버 80번 이메일 110번 FTP 21번) 
    • Primary Role: Ensuring reliable communication and data transfer between devices.
      • Flow Control and Congestion Control: Ensures the network isn't overwhelmed by controlling the rate of data transmission between devices.
      • Data Integrity, Connection Management
  • - 5계층 (세션계층Session) : 세션체결 , 통신방식 등을 결정, 동시에 여러 종류의 데이터(여러개의 파일)을 받을때 논리적으로 구분하고 병렬적으로 다운받을 수 있도록 하는 것
    • Primary Role: Managing and controlling the dialog between two applications.
  • - 6계층 (표현계층 Presentation) : 문자코드, 압축, 암호화 등의 데이터 변환 담당; 
  • - 7계층 (응용계층 Application) : 이메일, 파일전송, 웹사이트 열람 등 어플리케이션에 대한 서비스 제공; 어플리케이션 별로 필요한 데이터를 제공
    • Primary Role: Providing the interface for the user and ensuring that the data is presented in a readable and usable format.
      • Protocol Handling: Implements application-specific protocols such as HTTP, FTP, SMTP, etc., which dictate how different types of data should be transferred between applications.

OSI7은 개념적인 스펙이며 실제로 사용되는 것은 TCP/IP 스택이다.

 

 

글자가 깨질때 잠재적 원인

  1. HTML Form Encoding: If the form's character encoding is not set to UTF-8, the data might get encoded in a different format when submitted
  2. JSP Page Encoding: The JSP pages must specify UTF-8 encoding to correctly handle and display non-ASCII characters.
  3. Request Handling Encoding: The server-side code must set the request character encoding to UTF-8 to correctly interpret the incoming data.
    • 주로 개발자가 직접만들 웹서버간의 http통신에서 encoding error가 발생하는 경향이 있어보임
  4. Database Encoding: The database and tables must be configured to use UTF-8 encoding to store and retrieve non-ASCII characters correctly.
  5. JDBC Connection Encoding: The JDBC connection must be set to use UTF-8 encoding to correctly handle non-ASCII characters between the application and the database.

 

IP 프로토콜

- IP : InternetProtocol로 version4의 경우 0.0.0.0 ~256.256.256.256까지 8비트 4개의 32비트로 구성되어있음.

-- 자기 PC의 IP주소는 127.0.0.1이며, 도메인 name으로 DNS서버를 통해서 웹서버의 IP주소도 확인가능함(CLI ping daum.net으로 확인가능)

-- 현재 모바일,PC,태블릿 등 다수의 인터넷 기기 보급으로 인해 IPv4의 IP개수 부족으로 16비트 8개의 128비트로 구성된 IPv6가 도입됨

-- 그러나, IPv4가 보급된 현상황으부터 IPv6로 변경이 어려움. 때문에, 지역허브단위로 국제 IP주소를 부여하고 지역허브 내의 기기에는 local에서 정의되고 내부적으로만 유효한 IP주소를 구분하여 대응하고 있음.

 

TCP/ UDP

-TCP : 연결형 프로토콜(3way& 4way Handshake) 데이터의 전송순서 및 신뢰성 보장

-UDP : 비연결형 프로토콜, TCP보다 빠른 전송속도, 스트리밍/브로드케스팅에 주로 사용

 

 

HTTP(Hyper Text Transfer Protocol)

개념 : Application 계층에서 응용프로그램과 직접 소통하는 프로토콜로 hyptertext(다른 문서에 연결이 되는 문서)를 전송하기 위해 도입되었다. 현재는 hypertext를 위한 html 외에도 json과 같이 여러가지 형태의 데이터 전송에도 사용된다.

  • 특성1 : Server/Client 모델을 가정하여 Request/Response로 통신함; 프로토콜의 형식에 따라서 Client가 요청을 보내면 Server에서 응답
  • 특성2 : Connectionless(Stateless)특성 : HTTP는 한 프로토콜로 1회성 response와 request를 전제로 하기에 이전의 통신내용이 후속의 통신내용에 영향을 미치지않는다. 그러므로 로그인을 한 행위가 후속 통신에 저장되지 않기에 추가적으로 다른 기능으로 보완함.
    • HTTP1.1 개선점 : Connectionless를 보완하기 위해서 HTTP1.1부터 Keep Alive기능을 지원해서, 설정된 timeout시간까지는 TCP HandShake 재연결 과정없이 (IP는 네트워크 Layer에서 많이 쓰고 HTTP는 TCP를 주로 사용) 데이터 송수신이 가능해졌다. 따라서 HTTP N회 송수신을 위해서 TCP Handshake 과정을 N번 반복할 필요가 없어졌다.

 

HTTP 통신구조

  • HTTP통신의 내용은 ASC코드로 표현하도록 되어있어서 String형태이다. 그리고 줄바꿈으로 내용을 구분한다.
    • 첫번째 줄
      • request일시 HTTP method, URL(웹서버에서 보관하고 있는 resource의 가상적인 주소)
      • response일시 HTTP 버전, 요청의 상태코드, 상태코드에 해당하는 메세지
        • {status code : 1xx Informational, 2xx Success, 3xx Redirection, 4xx Client Errors, 5xx Server Errors}
    • 두번째줄~ 줄바꿈 이전 : header(해당 http에 대한 메타데이터)
    • 줄바꿈후 : requestbody(본문)

 

 

HTTP Method

  • Get Method : 정보읽어들이기 (Select)
    • 주로, 전달이 필요한 간단한 데이터를 원하는 URL뒤에 Parameter 형식으로 전달함. 이는 Get하고자하는 resource를 unique하게 식별하기 위해서임. "https://bsh6226.tistory.com/?type=post&returnURL=http://www.naver.com"
  • Post Method(Insert) : 데이터를 새로 생성할때 사용하거나 GET방식으로 URL에 넣기 민감한 정보를 Body에 숨길때 사용
    • 전달이 필요한 파라미터들을 HTTP body에 포함되어 사용자는 URL을 통해서 직접확인 불가능
  • 그 외 : Put Method (UPDATE), DELETE Method (DELETE)까지 HTTP Request는 4가지 Method가 존재한다.
  • URI(Uniform Resource Identifier) : 통합자원식별자, URL은 URI의 하위개념으로 URL은 웹에서 자원을 찾을때만 지칭함
    • URL- Path Variables: Typically used with RESTful endpoints to uniquely identify resources. 파라미터와 값을 /로 구분하여 파라미터들이 명시적으로 보이지 않음. (: /users/123) 
      • 여기서 resources는 주로 collection of data를 말함. 
    • URL - Query Parameters: Used to pass additional data for filtering, sorting, pagination, or other optional parameters. 끝에 물음표를 사용하여 parameter와 값을 구분하여 파라미터들이 명시적으로 보임 (/users?page=1&size=20). 
      • Get방식에서는 HTTP body를 사용하지않고 url을 통해서 parameter을 전달함. 이차이는
        • 1. restul서비스는 stateless하고 이 특성에 맞추어 get하고자하는 자원이 독특하다면 자원의 주소인 url 역시 독특해야한다. 
        • 2. 전달하고자하는 데이터가 비교적 단순하기에

HTTP 보안성

 

HTTP는 Statless로 통신이 끝나면 이전 작업을 기억하지 않음. 보안/인증을 통과했어도 이를 기억할 방법이 필요한데, Stateless를 보완하기 위한 기법이 쿠키와 세션임. HTTP Header 내에는 Connection(Keep-Alive),User-Agent(기기정보 및 브라우저 정보)와 같은 정보 외에도 Cookie라는 정보가 있다. 이를 사용해서 보안성을 유지할 수 있음. 

  • Cookie : a cookie is a small piece of data that a server sends to a user's web browser. The browser stores this data and sends it back to the server with subsequent requests to the same domain. Cookies are used to remember information about the user between HTTP requests
    • Cookie기반방법: 가령 사용자가 최초 로그인을 통해서 인증을 할때, 서버는 쿠키에 로그인 관련된 정보를 저장하도록 Set-Cookie 명령을 내릴 수 있음. 그러나 이방식은 쿠키에 로그인 관련정보를 직접적으로 저장하기 때문에, 보안에 취약함.  
  • Session : A session in the context of web development refers to a period of interaction between a user and a web application, typically identified and maintained by the server.
    • Session기반방법 :Session은 Cookie에 로그인 관련 정보가 아니라 Client가 로그인한 후 그에 해당하는 SessionID를 부여하고 이를 Cookie에 저장하여 사용자 인증을함. HTTP 통신이 노출된다고해도 ID,PW같은 로그인 정보가 유출되는 것을 막을 수 있음.
      • Session ID를 탈취하여 사용하는 경우에도 보안성이 유지가능한데, 이는 유저의 IP, ID, User-Agent 등 유저의 특성에 맞는 것들을 모두 총합하여 만들 Key값이기때문에 이것이 완전히 동일하지 않으면 SessionID가 동일하지 않으므로 SessionID 검증작업에서 걸림.
  • Expires설정(유효기간) : Cookie 정보는 서버에서 저장한 기간까지만 유효하고 그 이후에는 삭제됨. 설정이 없다면 브라우저 종료시에 삭제됨.

HTTPS (HyperText Transfer Protocol Over Secure Socket Layer)

  • HTTP는 모든 컨텐츠 내용이 ASC코드로 오픈되어 있기때문에, HTTP통신시 사용하는 TCP/IP 소켓 통신에서, 일반 텍스트 대신, SSL 또는 TSL 프로토콜 통신을 통해 데이터 암호화하여 송수신
  • HTTP는 80포트를 사용하지만, HTTPS 기본포트는 443

네트워크 보안

  • 대칭키(비밀키)
    • 키가 하나로, 암/복호화키 동일함. 이 비밀키를 전송하는 과정이 필요한데, 비밀키를 전송화는 과정이 유출되면 불안정한 측면이 있음.
    • 대표 암호화 알고리즘 : DES, 3DES, TDES, AES, SEED, ARIA 등
  • 비대칭키(공개키, 개인키)
    • 키가 두개로, 암/복호화키가 상이하다. 수신자가 공개키를 공개하면, 발신자는 공개키를 사용하여 암호화하고, 오로지 수신자의 개인키로만 복화하가 가능하여 수신자 외에는 내용을 이해할 수 없도록 만든다. 
    • 대표 암호화 알고리즘 : RSA, ECC 등

 

 

 

REST API

  • REST (Representational State Transfer) : '자원의 표현에 의한 상태전달'이라는 설계원칙. 개발자들 사이에서 웹서버 구현가이드.
    • Represntational State : Representation of data란 db의 data를 직접적으로 송수신하는 것이 아니라 json과 같은 특정한 포맷으로 담아서 전송한다는 의미로, client-server가 db에 종속적이지 않은 관계를 갖는다는 의미.
    • Resource-Based:  각각의 자원들은 각각의 HTTP URL을 통해 unique하게 명시되어 각 자원끼리 혼동이 없도록 명확화.
    • Standard HTTP Methods:  http method를 CRUD(create - post, read - get, update - put, delete - delete) Operation 의 의미에 부합하도록 사용
      • http method와 url은 모드 string parsine으로 식별하고, 웹서버에서 해당 method와 url에 특정 메소드를 맵핑하는 방식이기때문에, http method와 의미적으로 부합하지않는 로직을 구현할 수 있기에 이를 막고자 rest원칙을 권장
  • RESTful API : Rest 설계원칙을 충실히 따르는 API를 말한다. REST기반으로 마이크로 서비스나 OPEN API를 구현한 것.
    •  마이크로 서비스란 하나의 서비스를 생성하기 위해서 각 세부 기능을 데이터별로 서버를 분산하여 대용량의 요청을 빠르게 처리하며 서로 독립성을 유지하는 하도록 API로 분리한것.

Restful API 설계 예시

 

 

 

Common HTTP Request Headers

1. Host

  • Purpose: Specifies the domain name of the server (and optionally the TCP port number).
  • Example: Host: www.example.com
  • Necessity: Necessary
  • Explanation: Required in HTTP/1.1 to distinguish between different domains hosted on the same server (virtual hosting).

2. User-Agent

  • Purpose: Identifies the client software making the request to the server.
  • Example: User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
  • Necessity: Optional
  • Explanation: Useful for content adaptation, analytics, and security, but not strictly required for a request to be processed.

3. Accept

  • Purpose: Specifies the media types that the client is willing to receive from the server.
  • Example: Accept: application/json, text/plain, */*
  • Necessity: Optional
  • Explanation: Facilitates content negotiation allowing the server to select a compatible format based on client capabilities.

4. Accept-Language

  • Purpose: Specifies the language(s) the client prefers to receive.
  • Example: Accept-Language: en-US,en;q=0.5
  • Necessity: Optional
  • Explanation: Guides the server in delivering localized content that best fits the client’s language preferences.

5. Accept-Encoding

  • Purpose: Indicates what content encodings the client understands.
  • Example: Accept-Encoding: gzip, deflate
  • Necessity: Optional
  • Explanation: Essential for efficient content transmission, enabling the server to encode the response using an encoding that the client can decode.

6. Authorization

  • Purpose: Contains credentials for authenticating the client to the server.
  • Example: Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l
  • Necessity: Conditional
  • Explanation: Required when accessing protected resources that need authentication.

7. Content-Type

  • Purpose: Indicates the media type of the body of the request.
  • Example: Content-Type: application/json (for a POST request containing JSON data)
  • Necessity: Conditional
  • Explanation: Crucial for POST and PUT requests as it tells the server how to correctly interpret the request body.

8. Content-Length

  • Purpose: Indicates the size of the request body, in bytes.
  • Example: Content-Length: 348
  • Necessity: Conditional
  • Explanation: Required for requests that carry a body to inform the server of the expected size of the data being sent.

9. Connection

  • Purpose: Controls whether the network connection stays open after the current transaction finishes.
  • Example: Connection: keep-alive
  • Necessity: Optional
  • Explanation: Helps manage TCP connections efficiently, especially when multiple requests/responses are exchanged.

10. Cache-Control

  • Purpose: Directives for caching mechanisms in both requests and responses.
  • Example: Cache-Control: no-cache
  • Necessity: Optional
  • Explanation: Used to specify directives that must be obeyed by all caching mechanisms along the request-response chain.

11. Referer

  • Purpose: Indicates the address of the previous web page from which a link to the currently requested page was followed.
  • Example: Referer: http://www.example.com/index.html
  • Necessity: Optional
  • Explanation: Useful for analytical purposes and for controlling access based on referrer, but can be omitted for privacy.

12. Cookie

  • Purpose: Sends stored cookies from the client to the server.
  • Example: Cookie: name=value; name2=value2
  • Necessity: Conditional
  • Explanation: Essential for maintaining session state or managing user-specific data across multiple requests.

Common HTTP Response Headers

1. Status-Line

  • Purpose: Indicates the result of the request and the status of the response.
  • Example: HTTP/1.1 200 OK
  • Necessity: Necessary
  • Explanation: Every HTTP response begins with a status line, which includes the protocol version, a status code, and a text description (reason phrase). It is essential for indicating the outcome of the HTTP request.

2. Content-Type

  • Purpose: Specifies the media type of the response content.
  • Example: Content-Type: application/json
  • Necessity: Necessary
  • Explanation: Essential to ensure that the client correctly interprets the data included in the body of the response.

3. Content-Length

  • Purpose: Specifies the length of the response body in octets (bytes).
  • Example: Content-Length: 1234
  • Necessity: Conditional
  • Explanation: Important for indicating how much data the client should expect to receive, particularly relevant for connection management and for clients to know when a message is complete.

4. Content-Encoding

  • Purpose: Specifies any encodings that have been applied to the response body.
  • Example: Content-Encoding: gzip
  • Necessity: Optional
  • Explanation: Useful when the response body has been compressed, which can enhance transmission speed and efficiency.

5. Set-Cookie

  • Purpose: Sends cookies from the server to the client.
  • Example: Set-Cookie: SessionId=xyz123; Expires=Wed, 09 Jun 2021 10:18:14 GMT
  • Necessity: Conditional
  • Explanation: Necessary for managing session state or user preferences across multiple requests.

6. Cache-Control

  • Purpose: Specifies directives for caching mechanisms.
  • Example: Cache-Control: no-cache
  • Necessity: Optional
  • Explanation: Provides rules for caching in both requests and responses, such as preventing caching or specifying caching duration.

7. Expires

  • Purpose: The date/time after which the response is considered stale.
  • Example: Expires: Thu, 01 Dec 2024 16:00:00 GMT
  • Necessity: Optional
  • Explanation: Helps control caching by specifying when content should be considered outdated.

8. Last-Modified

  • Purpose: The date and time at which the origin server believes the resource was last modified.
  • Example: Last-Modified: Tue, 15 Nov 2020 12:45:26 GMT
  • Necessity: Optional
  • Explanation: Useful for validating cached copies of resources, enabling more efficient caching mechanisms by the client.

9. ETag

  • Purpose: Provides an entity tag for the version of the resource.
  • Example: ETag: "686897696a7c876b7e"
  • Necessity: Optional
  • Explanation: Facilitates cache validation and optimized caching by allowing clients to make conditional requests to check if the content has changed.

10. Location

  • Purpose: Indicates where a newly created or moved resource is located.
  • Example: Location: http://www.example.com/index.html
  • Necessity: Conditional
  • Explanation: Essential for redirecting the client to a different URL, particularly after POST requests that result in the creation of a resource.

11. Server

  • Purpose: Describes the software used by the origin server handling the request.
  • Example: Server: Apache/2.4.1 (Unix)
  • Necessity: Optional
  • Explanation: Provides information about the server software, but not required for the functionality of the response.

12. WWW-Authenticate

  • Purpose: Indicates the authentication method that should be used to gain access to a resource.
  • Example: WWW-Authenticate: Basic realm="Access to the staging site"
  • Necessity: Conditional
  • Explanation: Required when the server responds with a 401 Unauthorized status and needs to provide the authentication method required.

 

 

 

기타프로토콜

POP3, IMAP MIME FTP

 

 

 

 

웹 브라우저의 전체 동작과정 정리

1. 웹브라우저에 입력된 String URL은 DNS프로토콜을 사용해 IP주소로 변환된ㄷ.

2. HTTP request는 운영체제의 네트워크 스택에 따라서 HTTP - TCP - IP - Ethernet을 전기신호로 변환, 전송한다

 

3. 웹브라우저 내에서의 동작  - DOM : Document Object Model과 Virtual DOM;

3.1 웹브라우저는 tag로 이루어진 html 파일을 파싱하여  hierarchy를 갖는 Dom Tree를 생성한다.

3.2 CSS정보를 파싱하여 CSSOM tree를 생성하고 두가지 트리를 기반으로 Render Tree를 생성한다. 

3.3 Render Tree를 토대로 최종적으로 rendering을 한다.

3.4 js는 html과 css를 동적으로 변화시키는데, 그럴 경우 Dom tree변경 ~ Rendering과정을 javascript 동작만큼 계속해서 반복하여 Overhead를 발생시킨다. 이를 개선하기 위해서 Dom의 변경사항을 json형태로 임시저장해놓고(Virtual Dom) javascript가 더이상 동작하지 않을때 그때까지의 모든 변경사항을 한번에 DOM tree에 적용시켜 한번만 Rendering과정을 거친다. 

- react나 vue.js에서 이를 활용함

'개발기술 > Computer Science' 카테고리의 다른 글

CS공부 - 기타공부  (0) 2024.06.17
CS공부 - 운영체제  (0) 2024.06.16
CS공부 - 컴퓨터구조  (0) 2024.01.19
CS를 위한 이산수학 정리  (0) 2023.12.20