인터넷 제어 메세지 프로토콜(ICMP)

ICMP(Internet Control Message Protocol)

정의

네트워크 장치에서 네트워크 통신 문제를 진단하는 데 사용하는 네트워크 계층 프로토콜입니다. ICMP는 주로 데이터가 의도한 대상에 적시에 도달하는지 여부를 확인하는 데 사용됩니다. 일반적으로 ICMP 프로토콜은 라우터와 같은 네트워크 장치에서 사용됩니다. ICMP는 오류 보고 및 테스트에 아주 중요하지만, 분산 서비스 거부(DDoS) 공격에도 사용될 수 있습니다.

사용 목적

  • 오류보고:  두 장치가 인터넷을 통해 연결되면 ICMP는 데이터가 의도한 대상에 도달하지 못한 경우 전송하는 장치와 공유할 오류를 생성합니다.
  • 네트워크 진단 수행
    • 예시) traceroute, ping

참고: https://www.cloudflare.com/ko-kr/learning/ddos/glossary/internet-control-message-protocol-icmp/

MongoDB

MongoDB Installation

Using Docker

version: '3.1'

services:
  mongo:
    image: mongo
    container_name: local-mongo
    restart: always
    ports:
      - "27017:27017"
    environment:
      MONGO_INITDB_ROOT_USERNAME: <root username>
      MONGO_INITDB_ROOT_PASSWORD: <root password>
    volumes:
      - ~/workspace/dockerdata/mongo/data:/data/db
      - ~/workspace/dockerdata/mongo/mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js
    networks:
      - local-tier

  mongo-express:
    image: mongo-express
    container_name: local-mongo-express
    restart: always
    ports:
      - "8081:8081"
    environment:
      ME_CONFIG_MONGODB_SERVER: mongo
      ME_CONFIG_MONGODB_ADMINUSERNAME: <root username>
      ME_CONFIG_MONGODB_ADMINPASSWORD: <root password>
      ME_CONFIG_BASICAUTH_USERNAME: <mongo-express username>
      ME_CONFIG_BASICAUTH_PASSWORD: <mongo-express password>
    depends_on:
      - mongo
    networks:
      - local-tier


networks:
  local-tier:
    external: true

Mongosh Installation

$ brew install mongosh

Connection DB

Using Mongosh

Local MongoDB

$ mongosh
or
$ mongosh "mongodb://localhost:27017"
or 
$ mongosh --port 28015
or
$ mongosh --port 27017  --authenticationDatabase "admin" -u "myUserAdmin" -p

Remote MongoDB

$ mongosh "mongodb://mongodb0.example.com:28015"
or
$ mongosh --host mongodb0.example.com --port 28015
or 
$ mongosh "mongodb://mongodb0.example.com:28015" --username <name> --password <password> --authenticationDatabase <database>
or 
$ mongosh "mongodb://mongodb0.example.com.local:27017,mongodb1.example.com.local:27017,mongodb2.example.com.local:27017/?replicaSet=replA"

Create Database

mongodb 에는 database 를 새로 생성하기 위해서 create command 가 아닌 use command 를 사용해야 한다고 한다. 여기서 주의할 점은 새로 만든 database의 collection에 실제로 데이터를 insert 해야 그때 database 가 생성된다고 한다.

$ show dbs
admin 0.000GB
local  0.000GB

$ use practice

$ show dbs
admin 0.000GB
local  0.000GB

$ db.users.insertOne({name: 'onyou', age: 13})
completed in 246 ms

$ show dbs
admin 0.000GB
local  0.000GB
practice 0.000GB

Show Collection List

$ show collections

Create User

$ use practice
$ db.createUser(
  {
    user: "<username>",
    pwd:  passwordPrompt(),   // or cleartext password
    roles: [ { role: "readWrite", db: "practice" }]
  }
)

Show All Users

$ db.system.users.find()
[
  {
    _id: 'admin.root',
    userId: new UUID("0cb9029e-b564-4bd6-a02a-bb6b5cc7bef6"),
    user: 'root',
    db: 'admin',
    credentials: {
      'SCRAM-SHA-1': {
        iterationCount: 10000,
        salt: '/qLdMyJud2MZrr2kYOOywg==',
        storedKey: 'GMHBeOvJATNBAEb5ChBY0FXW+oA=',
        serverKey: 'xxZG120c6rXIUXvyQ3SmIpi9jEI='
      },
      'SCRAM-SHA-256': {
        iterationCount: 15000,
        salt: 'Jg71PCiiCOPLZgOX+Oxq9b5tsc5U6PVNCd7c6A==',
        storedKey: 'mwXKRebeyBaKfcU9kbKi4ckq2pAFBqTWmW7kiOQ55tc=',
        serverKey: 'dZ5O7vLpmW8UWTbnzs11Rvre4iuQvR4VTqiZ2bDgHaQ='
      }
    },
    roles: [ { role: 'root', db: 'admin' } ]
  },
  {
    _id: 'practice.user1',
    userId: new UUID("ed94f7ca-d97f-431b-bd6f-2c560c71009f"),
    user: 'user1',
    db: 'practice',
    credentials: {
      'SCRAM-SHA-1': {
        iterationCount: 10000,
        salt: '9eQ6D/YFM4Ryx/BIZv2LIA==',
        storedKey: 'QDXBzc2iTRZEhh/RhU7IA2Ljff8=',
        serverKey: 'PqmvTjWx47cwdErcpTSAty58jes='
      },
      'SCRAM-SHA-256': {
        iterationCount: 15000,
        salt: 'UyUiZ/G50MWoYo3B+nz81ilQGkq6JbcI6fU2xw==',
        storedKey: 'CUr7E+LvwyV2PctgZWNcWXniszpxMhEZVro9HJk8C3A=',
        serverKey: 'O6DAttVI44o14qsKimnoc1AJzfYTM9zmwwd13zwjaiA='
      }
    },
    roles: [ { role: 'readWrite', db: 'practice' } ]
  }
]

Insert

Mutiple Documents

db..insertMany({…})

$ db.users.insertMany([
...    {name: 'rm', age: 29},
...    {name: 'jin', age: 31},
...    {name: 'suga', age: 30},
...    {name: 'j-hop', age: 29},
...    {name: 'jimin', age: 28},
...    {name: 'v', age: 28},
...    {name: 'jk', age: 26},
... ])
{
  acknowledged: true,
  insertedIds: {
    '0': ObjectId("647b12a121feb6db1e68be5f"),
    '1': ObjectId("647b12a121feb6db1e68be60"),
    '2': ObjectId("647b12a121feb6db1e68be61"),
    '3': ObjectId("647b12a121feb6db1e68be62"),
    '4': ObjectId("647b12a121feb6db1e68be63"),
    '5': ObjectId("647b12a121feb6db1e68be64"),
    '6': ObjectId("647b12a121feb6db1e68be65")
  }
}

Single Document

db..insertOne({…})

$ db.users.insertOne({name: 'eujin', age: 6})
{
  acknowledged: true,
  insertedId: ObjectId("647b134421feb6db1e68be66")
}

Select

Find All

db..find()

$ db.users.find()
[
  { _id: ObjectId("647b0864e5835527d662b96f"), name: 'onyou', age: 13 },
  { _id: ObjectId("647b12a121feb6db1e68be5f"), name: 'rm', age: 29 },
  { _id: ObjectId("647b12a121feb6db1e68be60"), name: 'jin', age: 31 },
  { _id: ObjectId("647b12a121feb6db1e68be61"), name: 'suga', age: 30 },
  { _id: ObjectId("647b12a121feb6db1e68be62"), name: 'j-hop', age: 29 },
  { _id: ObjectId("647b12a121feb6db1e68be63"), name: 'jimin', age: 28 },
  { _id: ObjectId("647b12a121feb6db1e68be64"), name: 'v', age: 28 },
  { _id: ObjectId("647b12a121feb6db1e68be65"), name: 'jk', age: 26 },
  { _id: ObjectId("647b134421feb6db1e68be66"), name: 'eujin', age: 6 }
]

Filter data

db..find({ … filter condition … })

$ db.users.find({ _id: ObjectId("647b0864e5835527d662b96f") })
[
  { _id: ObjectId("647b0864e5835527d662b96f"), name: 'onyou', age: 13 }
]

$ db.users.find({ name: 'jimin'})
[
  { _id: ObjectId("647b12a121feb6db1e68be63"), name: 'jimin', age: 28 }
]

$ db.users.find({ age: { $lt: 30 }, name : { $regex: /^j/i }})
[
  { _id: ObjectId("647b12a121feb6db1e68be62"), name: 'j-hop', age: 29 },
  { _id: ObjectId("647b12a121feb6db1e68be63"), name: 'jimin', age: 28 },
  { _id: ObjectId("647b12a121feb6db1e68be65"), name: 'jk', age: 26 }
]

Project Field

특정 필드만 출력할 때 사용하기

db.collection.find(query, projection, options)

$ db.users.find( { }, { _id: 0 } ) // 0: 출력 결과물에서 제외처
[
  { name: 'estel', age: 39 },
  { name: 'rm', age: 29 },
  { name: 'jin', age: 31 },
  { name: 'suga', age: 30 },
  { name: 'j-hop', age: 29 },
  { name: 'jimin', age: 28 },
  { name: 'v', age: 28 },
  { name: 'jk', age: 26 },
  { name: 'eujin', age: 6 },
  { name: 'onyou', age: 13 }
]

커버링 인덱스(Covering Index)

query에서 검색된 모든 column(select, where, order by, group by 등)을 포함하는 인덱스입니다. query는 인덱스 값을 포인터로 사용하여 전체 테이블 행을 찾는 대신 인덱스 구조(메모리에 존재)에서 값을 반환하므로 디스크 I/O를 절약(디스크까지 탐색을 안 해도 됩니다.)할 수 있습니다. InnoDB 보조 인덱스에는 primary key column도 포함되므로 InnoDB는 이 최적화 기법을 MyISAM보다 더 많은 인덱스에 적용할 수 있습니다. InnoDB는 트랜잭션에 의해 수정된 테이블에 대한 쿼리에는 해당 트랜잭션이 종료될 때까지 이 기술을 적용할 수 없습니다.

예시

create index idx_xxx_01 test on (column1, colmun2);

select a.*
  from (select column1, column2
          from test 
         where a.column1 = xxx
           and a.colmun2 = xxx
      order by a.column1
       ) b join test a 
    on (b.column1 = a.column1 and b.column2 = a.colmun2);

위 예제에서 join 에 해당하는 b 의 구문이 covering index 가 사용된다.

참고

IntelliJ shortcut

command + P : 메소드 시그니처 확인

command + B : Go to Declaration or Usages

command + [ : back 직전에 보고 있던 코드로 돌아가기

command + D : 코드 중복해서 복사하기

shift + command + A : Actions

command + 1 : Go to Project

command + z : undo choose lookup item. 방금 처리한 거를 undo 하기

command + E: Recent File

shift(⇧) + command(⌘) + returun(↩) : Create code constructs with completion

option + delete : Delete to Word Start

command + F6 Change Signature

command + shift(⇧) + / : Comment Block

command + shift(⇧) + 8 + shift(⇧) + up(down)하고서 타이핑 : multiline select 하여 작업하기

command + shift(⇧) + 8: Edit > Column Selection Mode

shift(⇧) + F6 : in-place rename parameter

command + F12 : 메소드 검색하여 찾기

shift(⇧) + command + returun(↩): Create code constructs with completion

netstat(network statistics)

netstat 커맨드는 문제 해결 및 구성에 사용되는 네트워킹 도구이다. 네트워크를 통한 연결(connection)에 대한 모니터링 도구로도 사용할 수 있다. 이 명령은 수신(incoming) 및 발신(outgoing) 연결(connection), 라우팅 테이블(routing tables), 포트 수신(port listening)  및 사용량 통계(usage statistics) 모두에 일반적으로 사용된다.

netstat의 기본 사용법과 가장 많이 사용되는 몇 가지 사례를 살펴본다.

모든 연결 및 수신 대기중인 port 출력

TCP와 UDP를 사용하는 모든 연결(Established) 및 수신 대기(Listening) 중인 port 에 대한 목록을 출력한다.

netstat -a

$ netstat -a
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 0.0.0.0:40002           0.0.0.0:*               LISTEN
tcp        0      0 localhost:38597         0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:sunrpc          0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:ssh             0.0.0.0:*               LISTEN
tcp        0      0 localhost:smtp          0.0.0.0:*               LISTEN
tcp        0      0 ip-100-0-100-105.:56014 12.95.195.145:https     ESTABLISHED
tcp        0      0 ip-100-0-100-105.:56468 12.95.194.65:https      ESTABLISHED
tcp        0      0 ip-100-0-100-105.:47026 12.95.195.109:https     ESTABLISHED
tcp       54      0 ip-100-0-100-105.:42868 s3.ap-northeast-2:https CLOSE_WAIT
tcp        0      0 ip-100-0-100-105.ap:ssh ip-100-0-1-10.ap-:51790 ESTABLISHED
tcp6       0      0 [::]:40002              [::]:*                  LISTEN
tcp6       0      0 [::]:sunrpc             [::]:*                  LISTEN
tcp6       0      0 [::]:ssh                [::]:*                  LISTEN
udp        0      0 0.0.0.0:bootpc          0.0.0.0:*
udp        0      0 0.0.0.0:sunrpc          0.0.0.0:*
udp        0      0 localhost:323           0.0.0.0:*
udp        0      0 0.0.0.0:838             0.0.0.0:*
udp6       0      0 [::]:sunrpc             [::]:*
udp6       0      0 localhost:323           [::]:*
udp6       0      0 ip-100-0-:dhcpv6-client [::]:*
udp6       0      0 [::]:838                [::]:*
Active UNIX domain sockets (servers and established)
Proto RefCnt Flags       Type       State         I-Node   Path
unix  2      [ ACC ]     STREAM     LISTENING     18448    /var/run/lsm/ipc/simc
unix  2      [ ACC ]     STREAM     LISTENING     129353489 /run/docker.sock
unix  2      [ ACC ]     STREAM     LISTENING     18450    /var/run/lsm/ipc/sim
unix  2      [ ]         DGRAM                    129366551 /run/chrony/chronyd.sock
unix  2      [ ACC ]     STREAM     LISTENING     1840     /var/lib/gssproxy/default.sock
unix  2      [ ACC ]     STREAM     LISTENING     1841     /run/gssproxy.sock
unix  2      [ ]         DGRAM                    631610188 @007bd
unix  2      [ ACC ]     STREAM     LISTENING     19889    public/cleanup
unix  2      [ ACC ]     STREAM     LISTENING     129362221 /var/lib/amazon/ssm/ipc/health
unix  2      [ ACC ]     STREAM     LISTENING     19892    public/qmgr
unix  2      [ ACC ]     STREAM     LISTENING     129362222 /var/lib/amazon/ssm/ipc/termination
unix  2      [ ACC ]     STREAM     LISTENING     19914    public/flush
unix  2      [ ACC ]     STREAM     LISTENING     19929    public/showq
unix  2      [ ACC ]     STREAM     LISTENING     631      /run/lvm/lvmetad.socket
unix  2      [ ]         DGRAM                    637      /run/systemd/shutdownd
unix  2      [ ACC ]     STREAM     LISTENING     648      /run/lvm/lvmpolld.socket
unix  2      [ ACC ]     STREAM     LISTENING     631616612 /var/run/docker/metrics.sock
unix  2      [ ACC ]     STREAM     LISTENING     631613330 /run/containerd/s/fcb9b1129a111b100115c3mot456f726c1e07ede5bc8b00e234e567890e64e18

TCP port 연결만 출력

-t 옵션을 사용한다.

netstat -at

$ netstat -at
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 0.0.0.0:40002           0.0.0.0:*               LISTEN
tcp        0      0 localhost:38597         0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:sunrpc          0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:ssh             0.0.0.0:*               LISTEN
tcp        0      0 localhost:smtp          0.0.0.0:*               LISTEN
tcp        0      0 ip-100-0-100-105.:40884 22.95.195.100:https     TIME_WAIT
tcp        0      0 ip-100-0-100-105.:47026 22.95.195.109:https     ESTABLISHED
tcp       54      0 ip-100-0-100-105.:42868 s3.ap-northeast-2:https CLOSE_WAIT
tcp        0      0 ip-100-0-100-105.:43126 22.95.194.61:https      ESTABLISHED
tcp        0      0 ip-100-0-100-105.ap:ssh ip-200-0-1-10.ap-:51790 ESTABLISHED
tcp        0      0 ip-100-0-100-105.:40912 22.95.195.100:https     ESTABLISHED
tcp6       0      0 [::]:40002              [::]:*                  LISTEN
tcp6       0      0 [::]:sunrpc             [::]:*                  LISTEN
tcp6       0      0 [::]:ssh                [::]:*                  LISTEN

이렇게 하면 TCP 연결만 훨씬 더 사용자 친화적으로 읽을 수 있습니다.

UDP port 연결말 출력

– u 옵션을 사용한다.

netstat -au

$ netstat -au
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
udp        0      0 0.0.0.0:bootpc          0.0.0.0:*
udp        0      0 0.0.0.0:sunrpc          0.0.0.0:*
udp        0      0 localhost:323           0.0.0.0:*
udp        0      0 0.0.0.0:838             0.0.0.0:*
udp6       0      0 [::]:sunrpc             [::]:*
udp6       0      0 localhost:323           [::]:*
udp6       0      0 ip-100-0-:dhcpv6-client [::]:*
udp6       0      0 [::]:838                [::]:*

모든 active Listening port 출력

-l 옵션을 사용한다.
모든 active listening port(TCP 및 UDP 모두)를 나열한다.

netstat -l

$ netstat -l
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 0.0.0.0:40002           0.0.0.0:*               LISTEN
tcp        0      0 localhost:38597         0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:sunrpc          0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:ssh             0.0.0.0:*               LISTEN
tcp        0      0 localhost:smtp          0.0.0.0:*               LISTEN
tcp6       0      0 [::]:40002              [::]:*                  LISTEN
tcp6       0      0 [::]:sunrpc             [::]:*                  LISTEN
tcp6       0      0 [::]:ssh                [::]:*                  LISTEN
udp        0      0 0.0.0.0:bootpc          0.0.0.0:*
udp        0      0 0.0.0.0:sunrpc          0.0.0.0:*
udp        0      0 localhost:323           0.0.0.0:*
udp        0      0 0.0.0.0:838             0.0.0.0:*
udp6       0      0 [::]:sunrpc             [::]:*
udp6       0      0 localhost:323           [::]:*
udp6       0      0 ip-100-0-:dhcpv6-client [::]:*
udp6       0      0 [::]:838                [::]:*
Active UNIX domain sockets (only servers)
Proto RefCnt Flags       Type       State         I-Node   Path
unix  2      [ ACC ]     STREAM     LISTENING     18448    /var/run/lsm/ipc/simc
unix  2      [ ACC ]     STREAM     LISTENING     529353489 /run/docker.sock
unix  2      [ ACC ]     STREAM     LISTENING     18450    /var/run/lsm/ipc/sim
unix  2      [ ACC ]     STREAM     LISTENING     1840     /var/lib/gssproxy/default.sock
unix  2      [ ACC ]     STREAM     LISTENING     1841     /run/gssproxy.sock
unix  2      [ ACC ]     STREAM     LISTENING     19889    public/cleanup
unix  2      [ ACC ]     STREAM     LISTENING     529362221 /var/lib/amazon/ssm/ipc/health
unix  2      [ ACC ]     STREAM     LISTENING     19892    public/qmgr

원하는 프로토콜에 따라 -t 및 -u 옵션을 추가하여 수신 포트에도 필터를 적용할 수 있습니다.

Active Listening TCP port 만 출력

netstat -lt

$ netstat -lt
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 0.0.0.0:40002           0.0.0.0:*               LISTEN
tcp        0      0 localhost:38597         0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:sunrpc          0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:ssh             0.0.0.0:*               LISTEN
tcp        0      0 localhost:smtp          0.0.0.0:*               LISTEN
tcp6       0      0 [::]:40002              [::]:*                  LISTEN
tcp6       0      0 [::]:sunrpc             [::]:*                  LISTEN
tcp6       0      0 [::]:ssh                [::]:*                  LISTEN

Active Listening UDP port 만 출력

netstat -lu

$ netstat -lu
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
udp        0      0 0.0.0.0:bootpc          0.0.0.0:*
udp        0      0 0.0.0.0:sunrpc          0.0.0.0:*
udp        0      0 localhost:323           0.0.0.0:*
udp        0      0 0.0.0.0:838             0.0.0.0:*
udp6       0      0 [::]:sunrpc             [::]:*
udp6       0      0 localhost:323           [::]:*
udp6       0      0 ip-100-0-:dhcpv6-client [::]:*
udp6       0      0 [::]:838                [::]:*

PID/프로그램명을 이용한 서비스(Socket) 출력

문제 해결에 매우 유용한 방법은 서비스를 PID별로 나열하는 것입니다. 이렇게 하려면 다음 명령을 사용하세요.

netstat -tp

$ netstat -tp
Active Internet connections (w/o servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 ip-100-0-100-103.:60734 22.15.100.109:https     ESTABLISHED 4108/ssm-agent-work
tcp        0      0 ip-100-0-100-103.:48722 22.15.194.54:https      ESTABLISHED 4108/ssm-agent-work
tcp        0    180 ip-100-0-100-103.ap:ssh ip-100-0-1-10.ap-:37674 ESTABLISHED 5316/sshd: ec2-user
tcp       54      0 ip-100-0-100-103.:40272 s3.ap-northeast-2:https CLOSE_WAIT  4009/codedeploy-age
tcp        0      0 ip-100-0-100-103.:59812 22.15.100.138:https     ESTABLISHED 4009/codedeploy-age
tcp        0      0 ip-100-0-100-103.:60676 instance-data.ap-n:http TIME_WAIT   -

ip address와 port 를 숫자로 출력

-n 옵션을 이용하여 ip address와 port를 숫자로 출력한다.

netstat -n

$ netstat -np
Active Internet connections (w/o servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 100.0.100.103:60734     22.25.105.109:443       ESTABLISHED 4108/ssm-agent-work
tcp        0      0 100.0.100.103:60730     22.25.105.145:443       ESTABLISHED 4009/codedeploy-age
tcp        0      0 100.0.100.103:22        200.0.1.10:37674        ESTABLISHED 5316/sshd: ec2-user
tcp        0      0 100.0.100.103:48910     22.25.104.54:443        ESTABLISHED 4108/ssm-agent-work
tcp       54      0 100.0.100.103:40272     52.219.60.65:443        CLOSE_WAIT  4009/codedeploy-age
tcp        0      0 100.0.100.103:44748     22.25.107.186:443       TIME_WAIT   -

netstat + grep

netstat와 grep의 조합은 포트에서 listening 프로그램 갯수를 찾는 데 매우 일반적으로 사용됩니다. 표준 netstat -ap를 실행한 다음 grep로 파이프하여 검색 키를 찾습니다.
-p 옵션은 프로세스에 관한 PID(Program Name)를 출력합니다.
이 예제에서는 http를 사용합니다:

$ netstat -ap | grep http
tcp        0      0 ip-200-0-100-203.:60734 52.95.195.109:https     ESTABLISHED 4108/ssm-agent-work
tcp        0      0 ip-200-0-100-203.:35824 52.95.194.65:https      ESTABLISHED 4108/ssm-agent-work
tcp        0      0 ip-200-0-100-203.:60650 52.95.195.145:https     ESTABLISHED 4009/codedeploy-age
tcp       54      0 ip-200-0-100-203.:40272 s3.ap-northeast-2:https CLOSE_WAIT  4009/codedeploy-age
tcp        0      0 ip-200-0-100-203.:47884 52.95.197.175:https     TIME_WAIT   -

이제 연결 및 수신 포트를 보는 방법을 알았으니 통계 가져오기에 대해 살펴보겠습니다.

protocol 통계 정보

protocol별로 정렬된 네트워크 통계 정보

프로토콜별로 정렬된 네트워크 통계를 가져와서 보려면 다음을 사용하세요.

netstat -s

$ netstat -s
Ip:
    2483807692 total packets received
    1 with invalid addresses
    2422928124 forwarded
    0 incoming packets discarded
    60879567 incoming packets delivered
    2478983887 requests sent out
    31 dropped because of missing route
Icmp:
    341 ICMP messages received
    0 input ICMP message failed.
    ICMP input histogram:
        destination unreachable: 340
        echo requests: 1
    354 ICMP messages sent
    0 ICMP messages failed
    ICMP output histogram:
        destination unreachable: 353
        echo replies: 1
IcmpMsg:
        InType3: 340
        InType8: 1
        OutType0: 1
        OutType3: 353
Tcp:
    2283976 active connections openings
    353 passive connection openings
    169 failed connection attempts
    16611 connection resets received
    4 connections established
    55092049 segments received
    52387298 segments send out
    89827 segments retransmited
    0 bad segments received.
    5979616 resets sent
Udp:
    5786890 packets received
    351 packets to unknown port received.
    0 packet receive errors
    5792041 packets sent
    0 receive buffer errors
    0 send buffer errors
UdpLite:
TcpExt:
    7690 packets pruned from receive queue because of socket buffer overrun
    318193 TCP sockets finished time wait in fast timer
    9110 delayed acks sent
    25 delayed acks further delayed because of locked socket
    Quick ack mode was activated 13366 times
    24052107 packet headers predicted
    14166848 acknowledgments not containing data payload received
    3227098 predicted acknowledgments
    33 times recovered from packet loss by selective acknowledgements
    1 congestion windows recovered without slow start by DSACK
    86 congestion windows recovered without slow start after partial ack
    1 timeouts after SACK recovery
    49 fast retransmits
    3 retransmits in slow start
    1059 other TCP timeouts
    TCPLossProbes: 88887
    TCPLossProbeRecovery: 38
    13368 DSACKs sent for old packets
    1 DSACKs sent for out of order packets
    51763 DSACKs received
    1469138 connections reset due to unexpected data
    16416 connections reset due to early user close
    106 connections aborted due to timeout
    TCPDSACKIgnoredNoUndo: 51758
    TCPSpuriousRTOs: 1
    TCPSackShiftFallback: 36
    TCPBacklogDrop: 68
    TCPRcvCoalesce: 11404050
    TCPOFOQueue: 63214
    TCPOFOMerge: 1
    TCPAutoCorking: 3400835
    TCPFromZeroWindowAdv: 7017
    TCPToZeroWindowAdv: 7017
    TCPWantZeroWindowAdv: 20209
    TCPSynRetrans: 91
    TCPOrigDataSent: 20238336
    TCPHystartTrainDetect: 14
    TCPHystartTrainCwnd: 455
    TCPACKSkippedSeq: 125
    TCPKeepAlive: 3321901
IpExt:
    InOctets: 1050564296337
    OutOctets: 1923989515491
    InNoECTPkts: 2942482273

원하는 프로토콜에 따라 -t 및 -u 옵션을 추가하여 연결/포트에도 필터를 적용할 수 있습니다.

TCP 통계 정보

netstat -st

$ netstat -st
IcmpMsg:
    InType3: 340
    InType8: 1
    OutType0: 1
    OutType3: 353
Tcp:
    2283985 active connections openings
    353 passive connection openings
    169 failed connection attempts
    16611 connection resets received
    4 connections established
    55092299 segments received
    52387574 segments send out
    89827 segments retransmited
    0 bad segments received.
    5979642 resets sent
UdpLite:
TcpExt:
    7690 packets pruned from receive queue because of socket buffer overrun
    318196 TCP sockets finished time wait in fast timer
    9122 delayed acks sent
    25 delayed acks further delayed because of locked socket
    Quick ack mode was activated 13366 times
    24052200 packet headers predicted
    14166915 acknowledgments not containing data payload received
    3227132 predicted acknowledgments
    33 times recovered from packet loss by selective acknowledgements
    1 congestion windows recovered without slow start by DSACK
    86 congestion windows recovered without slow start after partial ack
    1 timeouts after SACK recovery
    49 fast retransmits
    3 retransmits in slow start
    1059 other TCP timeouts
    TCPLossProbes: 88887
    TCPLossProbeRecovery: 38
    13368 DSACKs sent for old packets
    1 DSACKs sent for out of order packets
    51763 DSACKs received
    1469145 connections reset due to unexpected data
    16416 connections reset due to early user close
    106 connections aborted due to timeout
    TCPDSACKIgnoredNoUndo: 51758
    TCPSpuriousRTOs: 1
    TCPSackShiftFallback: 36
    TCPBacklogDrop: 68
    TCPRcvCoalesce: 11404077
    TCPOFOQueue: 63214
    TCPOFOMerge: 1
    TCPAutoCorking: 3400854
    TCPFromZeroWindowAdv: 7017
    TCPToZeroWindowAdv: 7017
    TCPWantZeroWindowAdv: 20209
    TCPSynRetrans: 91
    TCPOrigDataSent: 20238450
    TCPHystartTrainDetect: 14
    TCPHystartTrainCwnd: 455
    TCPACKSkippedSeq: 125
    TCPKeepAlive: 3321919
IpExt:
    InOctets: 1050565553032
    OutOctets: 1923991947989
    InNoECTPkts: 2942493729

UDP 통계

$ netstat -su

$ netstat -su
IcmpMsg:
    InType3: 340
    InType8: 1
    OutType0: 1
    OutType3: 353
Udp:
    5786934 packets received
    351 packets to unknown port received.
    0 packet receive errors
    5792085 packets sent
    0 receive buffer errors
    0 send buffer errors
UdpLite:
IpExt:
    InOctets: 1050566403376
    OutOctets: 1923993611798
    InNoECTPkts: 2942501136

Raw 네트워크 통계

필터링된 데이터가 마음에 들지 않는다면 원시 통계를 가져오는 것도 고려해 보세요:

netstat -s –raw

$ netstat -s --raw
Ip:
    2483834485 total packets received
    1 with invalid addresses
    2422954264 forwarded
    0 incoming packets discarded
    60880220 incoming packets delivered
    2479010732 requests sent out
    31 dropped because of missing route
Icmp:
    341 ICMP messages received
    0 input ICMP message failed.
    ICMP input histogram:
        destination unreachable: 340
        echo requests: 1
    354 ICMP messages sent
    0 ICMP messages failed
    ICMP output histogram:
        destination unreachable: 353
        echo replies: 1
IcmpMsg:
        InType3: 340
        InType8: 1
        OutType0: 1
        OutType3: 353
UdpLite:
IpExt:
    InOctets: 1050567289299
    OutOctets: 1923995315711
    InNoECTPkts: 2942509140

Interface 를 통한 I/O 테이블 출력

-i 옵션은 문제 해결에 유용한 또 다른 플래그입니다. 인터페이스별 송수신 통계를 보려면 다음을 사용하세요:

netstat -i

$ netstat -i
Kernel Interface table
Iface      MTU    RX-OK RX-ERR RX-DRP RX-OVR    TX-OK TX-ERR TX-DRP TX-OVR Flg
docker0   1500 68678402      0      0 0      55006962      0      0      0 BMRU
eth0      9001 299047705      0      0 0      168268249      0      0      0 BMRU
lo       65536   170687      0      0 0        170687      0      0      0 LRU
vethc99b  1500   588242      0      0 0        458512      0      0      0 BMRU

이제 끝났습니다. netstat 명령은 Linux 네트워크 관리자라면 누구나 사용할 수 있는 사용하기 쉽고 강력한 도구입니다. 저는 문제 해결을 위해 스토리지 관리자로서 netstat를 광범위하게 사용했으며, 여러분도 이 도구를 유용하게 사용할 수 있을 것이라고 확신합니다. 최근 몇 년 동안 ss 명령이 더 이상 사용되지 않지만 네트워킹 도구 상자에서 여전히 찾을 수 있습니다. 좀 더 현대적인 방법을 알아보려면 다음 글에서 ss를 살펴볼 예정이니 계속 지켜봐 주세요!

참고

상태(state) 정보

state설명
LISTEN연결 요구를 기다리는 상태. port는 열려 있음.
ESTABLISHED서로 연결되어 있는 상태.
SYN_SENT클라이언트가 서버에 SYN 패킷을 보내고 연결을 요청한 상태
SYN_RECV서버가 클라이언트의 SYN 패킷으로 요청을 받은 후 응답으로 SYN/ACK 패킷을 보내고 클라이언트에게 ACK 를 받기 위해 기다리는 상태
TIME_WAIT이미 해당 사이트와 연결이 종료되었거나 다음 연결을 위해 기다리는 상태
CLOSE_WAIT원격의 연결 요청을 받고 연결이 종료되길 기다리는 상태
LAST_ACK연결이 종료되었고 승인을 기다리는 상태
CLOSED완전히 연결이 종료된 상태
출처: https://www.ictshore.com/wp-content/uploads/2016/12/1017-01-TCP_States_diagram.png
출처: https://totozhang.github.io/2016-01-23-tcp-connection-status-transit/TCPState2.png
출처: https://www.ictshore.com/wp-content/uploads/2016/12/1017-02-TCP_States_in_a_connection.png

원문: https://www.redhat.com/sysadmin/netstat?fbclid=IwAR0WabheUNxfUcfWXQe12Cv4-ZeKPNDgmsG69S-UNhOXzVg_7vtS90NKmZ8

네트워크 명령어

3-way handshaking 을 통해 원격 서버와의 연결을 확인할 수 있는 명령어

netstat -an | grep :

sudo tcpdump -n host

sudo tcpdump -n port

netstat

네트워크 접속, 라우팅 테이블, 네트워크 인터페이스의 통계

netstat -an | grep <remote server ip>:<port>
  • -a, –all: 사용중인 모든 포트
  • -l, –listening: listening 중인 모든 TCP/UDP/Unix Domain socket
  • -t, –tcp : listening 중인 TCP 소켓만 표시
  • -n: active TCP 연결을 표시하지만 주소와 포트 번호는 숫자로 표시되며 이름을 확인하려고 시도하지 않습니다.
  • -p: 프로그램 ID/PID
  • -r: 라우팅 테이블

자주 사용하는 경우

연결을 기다리는 목록과 프로그램

netstat -nap 

특정 포트가 사용 중에 있는지 확인 

netstat -an | grep <port>

TCP listening 상태의 포트와 프로그램

netstat -nlpt

tcpdump

포맷 양식

[Timestamp] [Protocol] [Src IP].[Src Port] > [Dst IP].[Dst Port]: [Flags], [Seq], [Ack], [Win Size], [Options], [Data Length]

[P.] – 이전 패킷을 확인하고 데이터를 전송하는 데 사용되는 Push Acknowledgement 패킷

[.] – ACK(승인)

[S] – SYN(연결 시작)

[P] – PSH(데이터 푸시)

[F] – FIN(연결 완료)

[R] – RST(연결 재설정)

[S.] – SYN-ACK(SynAcK 패킷)

[root@ip-100-0-100-100 ~]# tcpdump -n host 22.90.90.60
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on eth0, link-type EN10MB (Ethernet), capture size 262144 bytes


16:25:20.131624 IP 100.0.100.203.54792 > 22.90.90.60.https: Flags [S], seq 3124912201, win 26883, options [mss 8961,sackOK,TS val 3845158208 ecr 0,nop,wscale 7], length 0
16:25:20.134084 IP 22.90.90.60.https > 100.0.100.203.54792: Flags [S.], seq 1684534894, ack 3124912202, win 8190, options [mss 1460,nop,wscale 6,nop,nop,sackOK], length 0
16:25:20.134099 IP 100.0.100.203.54792 > 22.90.90.60.https: Flags [.], ack 1, win 211, length 0
16:25:20.134264 IP 100.0.100.203.54792 > 22.90.90.60.https: Flags [P.], seq 1:293, ack 1, win 211, length 292
16:25:20.136413 IP 22.90.90.60.https > 100.0.100.203.54792: Flags [.], ack 293, win 32763, length 0
16:25:20.136056 IP 22.90.90.60.https > 100.0.100.203.54792: Flags [.], ack 293, win 32763, length 0
16:25:20.136633 IP 22.90.90.60.https > 100.0.100.203.54792: Flags [P.], seq 1:97, ack 293, win 32763, length 96
16:25:20.136640 IP 100.0.100.203.54792 > 22.90.90.60.https: Flags [.], ack 97, win 211, length 0
16:25:20.136686 IP 22.90.90.60.https > 100.0.100.203.54792: Flags [.], seq 97:3017, ack 293, win 32763, length 2920
16:25:20.136690 IP 100.0.100.203.54792 > 22.90.90.60.https: Flags [.], ack 3017, win 256, length 0

도메인으로 IP 확인하는 방법

host naver.com

naver.com has address 223.130.200.104
naver.com has address 223.130.195.95
naver.com has address 223.130.200.107
naver.com has address 223.130.195.200
naver.com mail is handled by 10 mx1.naver.com.
naver.com mail is handled by 10 mx3.naver.com.
naver.com mail is handled by 10 mx2.naver.com.
ping naver.com -c 1

PING www.naver.com.nheos.com (223.130.200.107): 56 data bytes

--- www.naver.com.nheos.com ping statistics ---
1 packets transmitted, 0 packets received, 100.0% packet loss

nslookup naver.com
Server:		10.0.100.50
Address:	10.0.100.50#53

Non-authoritative answer:
Name:	naver.com
Address: 223.130.195.200
Name:	naver.com
Address: 223.130.195.95
Name:	naver.com
Address: 223.130.200.104
Name:	naver.com
Address: 223.130.200.107
dig any naver.com

; <<>> DiG 9.10.6 <<>> any naver.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 32453
;; flags: qr rd ra; QUERY: 1, ANSWER: 6, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;naver.com.			IN	ANY

;; ANSWER SECTION:
naver.com.		285	IN	A	223.130.200.107
naver.com.		285	IN	A	223.130.195.200
naver.com.		285	IN	A	223.130.200.104
naver.com.		285	IN	A	223.130.195.95
naver.com.		48413	IN	NS	ns2.naver.com.
naver.com.		48413	IN	NS	ns1.naver.com.

;; Query time: 31 msec
;; SERVER: 10.0.100.50#53(10.0.100.50)
;; WHEN: Thu Jun 01 14:33:26 KST 2023
;; MSG SIZE  rcvd: 138