BGP Messages

Within BGP (as per RFC 1771) there are four BGP message types. They are,

  • OPEN – Used to open a BGP communication session between peers. This is the first message sent by each side once the 3WHS is complete, and can be thought of as a HELLO. Only once each side has confirmed the OPEN message, the other message types can be exchanged. [1]
  • UPDATE – Used to exchange routing information, such as announce new routes or withdraw previously announced routes.
  • KEEPALIVE – Notifies BGP peers that a device is active. Used to keep sessions (i.e long periods with no updates) from expiring.
  • NOTIFICATION – This message is a result of an error condition occurring. These message types are used to close an active session, and also inform the peer to the reason why.

2. BGP Finite State Machine

BGP peers go through different finite states before a connection is
fully made. At each state, different BGP messages are sent back and
forth. Below is listed the different states, and at what states the
different BGP messages are sent.

The following states are:

  • Idle :
    BGP is waiting for a start event such as the admin enabling or
    resetting a BGP router. After the start event, BGP initializes its
    resources, resets the ConnectRetry timer,
    initiates a TCP connection, and listens for a connection from its peer.
    It then either switches to a Connect State, or falls back to the Idle
  • Connect : BGP is waiting for the TCP session to complete. If the connection is successful, the Open message
    is sent, and the state switches to OpenSent. If the session is not
    successful, then the state switches to Active. If nothing happens
    within the time that the ConnectRetry timer
    times out, then the TCP session is restarted, and the state stays the
    same. Other events will set the state back to the Idle State.
  • Active : BGP is still waiting for the TCP session to complete. Like the Connect State, once the connection is made, the Open message is sent, and the state switches to the OpenSent State. If ConnectRetry timer
    times out without a TCP session being made, the timer is reset and the
    state is switched to Connect (BGP still listens for a connection from
    the peer). Other events (such as the Stop event) will bring the state
    back to the Idle State. If the state is switching between Connect and
    Active, then it is a sign that there are reachability issues.
  • OpenSent : BGP has sent an Open message, and is waiting for one from the peer. When the peers Open Message is received, if it is ok it sends a Keepalive message, and resets the keepalive counter,
    and goes to the OpenConfirm state. If a TCP transport disconnect is
    received, the state will fall back to the Active state. If there are
    problems with the senders Open message, (bad BGP version, or bad AS),
    or the Holddown timer expires, or any other errors, then the system
    sends out an error notification, and resets to the Idle State.
    BGP figures out a bunch of things by comparing the two valid Open
    messages. First it looks at each holdtime fields, to come up with the
    value for the keepalive timer. If the values are not the same, the
    lowest of the two is chosen for both. It also looks at the two messages
    “My AS” field. If the values are the same, then the peer is an iBGP peer, and if they are different, it’s a eBGP peer.

  • OpenConfirm : BGP has just sent a Keepalive message, and is waiting for one back from its peer. Once the message arrives, the HoldTimer is reset, and Keepalives are sent as per the Keepalive timer.
    If a notification message, TCP transport disconnect message, or any
    other error is received, the state is switched to Idle, and sends a
    Notification message if neccessary. (All other error messages produce a
    Notification message with the error code as “finite state machine
  • Established : The state is switched to established as soon as a Update message is sent or received. The HoldTimer is reset after each Update message or Keepalive message.
    The state will change to Idle if the system receives a Notification
    message. It will also switch to idle, and send out a Notification
    message, if any errors are found in a received Update message, the
    Holddown time expires, or the router receives any other errors.

3. BGP Message Type

3.1 BGP Message Header

All BGP messages are encapsulated within the BGP Message Header.

Packet Overview:

  • Marker: Used to either authenticate incoming BGP
    messages, or detect loss of synchronization. If type=open, then the
    marker has no authentication and it is all ones. If not, then the
    marker uses an MD5 sig to authenticate the bgp packets.
  • Length: length of the bgp message. min 19 bytes (хедер with no message), and max of 4,096 bytes.
  • Type: messages purpose, (See RFC 1771)
    • 1: open
    • 2: update
    • 3: notification
    • 4: keepalive
  • Message Contents:
    One of the messages outlined in the following sections. Note that the
    keepalive has no message size, so when it is sent there is no message

3.2 Open Message

Packet Overview:

  • Version: [1-byte] This should be 4. All other
    versions of bgp (1-3) are considered obsolete and not used. Though this
    is currently set statically to 4, the standard says that the two peers
    will decide which is the highest version that they can both do, and
    then set to that version automatically.
  • My AS #: [2-byte] The Senders AS number.
  • Hold Time:
    [2-byte] The max number of seconds the session can be idle before it is
    torn down. If the bgp peers do not have the same hold time, then the
    lowest is used between the two of them. The minimum time is 3 seconds,
    the max is ???. A hold time of zero means the session will never time out. New incoming keepalive or update messages are what reset the holddown timer, which counts from 0 to the holddown time.
  • Identifier:
    [4-byte] aka: BGP Identifier, BGP ID, and Router ID (RID). The highest
    IP address for the router, or it’s highest loopback address.
  • Par Length: [1-byte] aka: Optional Parameter Length,
    Opt Parm Len. Length of the optional parameters field. A zero value
    indicates no optional parameters.
  • Optional Parameters: [variable length] Used in the
    BGP negotiation, and other extended capabilities like multiprotocol
    extensions and route refresh. An example would be the Authentication
    Information Parameter (type 1) which is used to authenticate the
    session with a BGP peer. It is made up of the Parameter Type, Parameter
    Length, and Parameter Value fields.

3.3 Update Message

The update message adds and/or removes routes.

There are three sections to the Update message; the unreachable routes,
the path attributes, and the NLRI (network layer reachability

The first is the unreachable routes section. It sends
information about routes that have become unreachable or withdrawn. The
second section lists the path attributes of new or known routes. An
example to a path attribute would be for a specific path . The last
section is the network layer reachability information (NLRI) which
lists the networks being advertised.

Open Message

As the two BGP peers establish a successful TCP connection ( completing the TCP 3-Way Handshake Process), the first message that is exchanged by both BGP peers is Open Message. Open message contains several fields that will be discussed later in this article. If the Open message is acceptable by the neighbor, a Keepalive message confirming the Open message is sent back the peer that received the Open message. The BGP Open message contain following fields.

Open Message

Version – This is a 8-bit field indicates the message’s BGP version number. The highest common version that both routers support is used. Most BGP implementations today use the current version is version 4.
My AS : This is a 16-bit field that indicates the sender peer’s  AS number. The peer router verifies this information; if it is not the AS number expected, the BGP session is terminated. 

Hold time : This is again a 16-bit field that indicates the maximum number of seconds that can elapse between the successive Keepalive or Update messages from the sender. Upon receipt of an Open message, the router calculates the value of the hold timer to use by using the smaller of its configured hold time and the hold time received in the Open message.BGP router identifier

BGP Identifier: This is a 32-bit field that indicates the sender’s BGP identifier. It is an IP address assigned to that router and is determined at startup. The BGP router ID is chosen the same way the OSPF router ID is chosen; it is the highest active IP address on the router, unless a loopback interface with an IP address exists, in which case is the highest such loopback IP address. Alternatively, the router ID can also be configured manually overriding the automatic selection.

Optional parameters : Contains Optional Parameters length and Optional Parameters the BGP supports. A length field indicates the total length of the optional parameters field in octets. The Optional parameters are Type, Length, and Value (TLV)-encoded. Few examples of an optional parameters are Route Refresh, BGP Multi-Protocol Support, Session authentication and 4-Byte AS Support.

Course Contents


  • Unit 1: Introduction to BGP
    • Introduction to BGP
    • Single/Dual (multi) homed connections
    • eBGP (external BGP)
    • eBGP Multi-Hop
    • iBGP (internal BGP)
    • How to read the BGP Table
    • How to advertise networks in BGP
    • iBGP Next Hop Self
    • BGP Auto-summary
  • Unit 2: BGP Neighbor Adjacency
    • BGP Neighbor Adjacency States
    • BGP Messages
    • Troubleshooting BGP Neighbor Adjacency
    • Troubleshooting BGP Route Advertisement
  • Unit 3: BGP Attributes
    • BGP Attributes and Path Selection
    • BGP Weight Attribute
    • BGP Local Preference
    • BGP AS Path Prepending
    • BGP Origin Code
    • BGP MED (metric) Attribute
    • Accumulated IGP Metric Attribute (AIGP)
  • Unit 4: BGP Communities
    • BGP Communities
    • BGP Community No Advertise
    • BGP Community No Export
    • BGP Community Local AS
  • Unit 5: BGP Filtering
    • BGP Regular Expressions
    • BGP Transit AS
    • BGP IPv6 route filtering
    • BGP AS Path Filter
    • BGP Extended Access-List Filtering
  • Unit 6: Advanced BGP Features
    • BGP Route Dampening
    • BGP Peer Groups
    • BGP Route Reflector
    • BGP Confederations
    • BGP Synchronization
    • BGP Backdoor Routes
    • MP-BGP (multi-protocol BGP)
    • BGP Private and Public AS Numbers
    • BGP Remove Private AS Numbers
    • BGP 4-byte AS numbers
    • BGP Soft Reconfiguration
    • BGP Route Refresh Capability
    • BGP Allow AS in
    • BGP AS Override
    • BGP Aggregate AS-SET
    • BGP Multipath eBGP and iBGP
  • Unit 7: BGP Convergence
    • BGP Next Hop Tracking
    • BGP Additional Paths
    • BGP PIC (Prefix Independent Convergence)

We’re Sorry, Full Content Access is for Members Only…

If you like to keep on reading, Become a Member Now! Here is why:

  • Learn any CCNA, CCNP and CCIE R&S Topic. Explained As Simple As Possible.
  • Try for Just $1. The Best Dollar You’ve Ever Spent on Your Cisco Career!
  • Full Access to our 747 Lessons. More Lessons Added Every Week!
  • Content created by Rene Molenaar (CCIE #41726)

Give Membership a try – it’s just $1 ►

683 Sign Ups in the last 30 days

100% Satisfaction Guaranteed!
You may cancel your monthly membership at any time.
No Questions Asked! BGP Neighbor Adjacency States
Previous Lesson Troubleshooting BGP Neighbor Adjacency
Next Lesson

1. BGP Overview:

that run the BGP process are called BGP Speakers. BGP Speakers that
talk directly with each others are called neighbors or peers.

BGP uses TCP port 179 for communication between routers. It
does not by itself know how to route traffic to its peers, instead uses
another routing protocol for this, like static routes or another
protocol (ie OSPF).

Watching BGP peers communicate with each other, we see these following common steps:

(1) When peers first attempt to connect, they exchange open messages to determine the connection parameters.

(1.1) BGP can also gracefully close a connection with a peer, allowing
all error messages to be sent between peers before the connection is
closed. This prevents the peer who was disconnected, from spending
cycles trying to reconnect with a router that will refuse all future

(2) When the BGP peers first establish a session, all the bgp routes are exchanged via an update message.

After that point only incremental updates are sent, still with the update message. So if a new network is added or one goes down, only that specific change is sent.

(3) While the peers are not sending routing information, keepalive messages’s
are regularly sent between them. This keeps the BGP session up,
allowing the peers to know that the routes are still valid. If the
session goes down (and stays down), then the router must assume that
the routes it learned from that neighbor are no longer valid. The
keepalive messages are small, not causing a strain on the routers or
the network.

BGP Neighbor Adjacency States

Just like OSPF or EIGRP, BGP establishes a neighbor adjacency with other routers before any routing information is exchanged. However BGP does not use broadcast or multicast for BGP neighbor discovery, instead, neighbors are configured manually, using TCP/179 for communication.

In order for two BGP systems to become neighbors, they will go through a series of BGP Neighbor Adjacency States. They are:

  1. Idle – BGP resources are initialized by the router. BGP inbound connection attempts are refused. BGP initiates a TCP connection to the peer.
  2. Connect – BGP waits for the 3WHS to complete. If successful, the OPEN message is sent to the peer and BGP moves to the OpenSent state. If unsuccessful we continue to the Active state. However, if the ConnectRetry expires, BGP will remain in this state, with the timer being reset and a new 3WHS being initiated.
  3. Active – The ConnectRetry timer is reset, and BGP returns to the Connect state.
  4. OpenSent – BGP waits for an OPEN message from its peer. Once received, BGP moves to the OpenConfirm state.
  5. OpenConfirm – BGP waits for a keepalive message from its peer. If received before the timeout expires, BGP moves to the Established state. Otherwise, BGP transitions to Idle.
  6. Established – Both peers exchange UPDATE messages. If there is an error within any of the UPDATE messages, the BGP peer will send a NOTIFICATION message and enter the Idle state.

Figure 1 – BGP States.  [2]


[1] “BGP – Cisco.” 8 Dec. 1999, . Accessed 3 Nov. 2017.
[2] “BGP Neighbor Adjacency States |” 2 Apr. 2015, . Accessed 18 Feb. 2018.

  • Author
  • Recent Posts

Rick Donato
Rick Donato Rick Donato is a Network Automation Architect/Evangelist and the founder of Packet Coders. Rick Donato
Latest posts by Rick Donato (see all)

  • How to Configure a BIND Server on Ubuntu – March 15, 2018
  • What is a BGP Confederation? – March 6, 2018
  • Cisco – What is BGP ORF (Outbound Route Filtering)? – March 5, 2018

Want to become a networking expert?

Here is our hand-picked selection of the best courses you can find online:
Cisco CCNA 200-301 Certification Gold Bootcamp
Complete Cyber Security Course – Network Security
Internet Security Deep Dive course
Python Pro Bootcamp
and our recommended certification practice exams:
AlphaPrep Practice Tests – Free Trial

Post navigation Cisco IOS – BGP Soft Reconfiguration

Our Recommended Complete Courses

Cisco CCNA 200-301 Gold Bootcamp:

Cisco CCNA Gold Bootcamp course

Complete Cyber Security Course – Network Security:

Complete Cyber Security Course - Network Security

Отношение соседства

Отношения соседства устанавливаются вручную для каждого соседа. При этом обязательно указывается автономная система соседа. По этой информации BGP определяет тип соседа:

  • Внутренний BGP сосед (iBGP-сосед) — сосед, который находится в той же AS. iBGP-соседи не обязательно должны быть непосредственно соединены.
  • Внешний BGP сосед (eBGP-сосед) — сосед, который находится в друго AS. По умолчанию, eBGP-соседи должны быть непосредственно соединены.

BGP выполняет такие проверки, когда формирует отношения соседства:

  1. Маршрутизатор должен получить запрос на TCP-соединение с адресом отправителя, указанным в списке соседей (команда neighbor).
  2. Номер AS локального маршрутизатора должен совпадать с номером AS, который указан на соседнем маршрутизаторе командой neighbor remote-as (это требование не соблюдается при настройках конфедераций).
  3. Идентификаторы маршрутизаторов (Router ID) не должны совпадать.
  4. Если настроена аутентификация, то соседи должны пройти её.

У первого пункта проверки есть некоторая особенность: только у одного из двух маршрутизаторов IP-адрес, указанный как адрес отправки обновлений, должен быть указан в команде neighbor другого маршрутизатора.

Состояния связи с соседями

  • IDLE – ничего не происходит
  • CONNECT – слушает и посылает пакеты TCP
  • ACTIVE – ждет ответа
  • OPEN SENT – сообщение OPEN отправлено
  • OPEN CONFIRM – сообщение OPEN получено
  • ESTABLISHED – стабильное состояние соседства

Update Message

An update message is used to advertise active or feasible prefixes to the other BGP peers. It is also used to withdraw the previously advertised routes that are presently gone unreachable. The fields of the Update message are listed below:
Withdrawn routes : The prefixes that have gone unreachable and now are withdrawn from the list of active routes (routing table).

Unfeasible routes length :  This field specifies the length of the Withdrawn Routes field in bytes. When it is set to 0, there are no routes withdrawn and the Withdrawn Routes field will also not seen as shown in the wireshark capture below.

Path attributes: Each prefix is associated with some BGP Path Attributes, for example Origin, AS_Path, Next_Hop, Local Preference, MED, Community etc. Some of the BGP Attributes are Well-Known and some are Optional.  Each path attribute contains the attribute type, attribute length, and attribute value (TLV). The attribute type consists of the attribute flags, followed by the attribute type code.
Network Layer Reachability Information (NLRI): NLRI field contains a list of prefixes that are up.

Update Message

Internet Security Deep Dive course:

Practical TLS - Internet Security Deep Dive


Конфедерации – это механизм, который позволяет обойти необходимость полной связности внутренних соседей BGP. При использовании конфедераций, исходная AS разбивается на подавтономные системы (sub-AS), внутри которых соседи должны быть соединены друг с другом в полносвязной топологии.

Создание конфедерации позволяет:

  • избежать необходимости создания полносвязной топологии между всеми iBGP-соседями,
  • всем iBGP-соседям выучить все iBGP-маршруты в AS,
  • предотвратить образование петель.

Python Pro Bootcamp:

Python Pro Bootcamp

Our Sponsors

Выбор маршрута

Характеристики процедуры выбора пути протоколом BGP:

  • В таблице BGP хранятся все известные пути, а в таблице маршрутизации — лучшие.
  • Пути выбираются на основании политик.
  • Пути не выбираются на основании пропускной способности.


На маршрутизаторе Cisco, если не настроены никакие политики выбора пути, выбор пути происходит таким образом (на каждый следующий шаг маршрутизатор переходит только при совпадении значений на предыдущем):

  1. Максимальное значение weight (локально для маршрутизатора).
  2. Максимальное значение local preference (для всей AS).
  3. Предпочесть локальный маршрут маршрутизатора (next hop =
  4. Кратчайший путь через автономные системы. (самый короткий AS_PATH)
  5. Минимальное значение origin code (IGP < EGP < incomplete).
  6. Минимальное значение MED (распространяется между автономными системами).
  7. Путь eBGP лучше чем путь iBGP.
  8. Выбрать путь через ближайшего IGP-соседа.
  9. Выбрать самый старый маршрут для eBGP-пути.
  10. Выбрать путь через соседа с наименьшим BGP router ID.
  11. Выбрать путь через соседа с наименьшим IP-адресом.


Если существует несколько маршрутов до одной сети назначения, будет выбран только один из них. Каждый шаг в алгоритме выбора лучшего маршрута пытается устранить все, кроме одного маршруты к пункту назначения. Если на шаге алгоритма маршрутов все еще больше одного, будет выполнен переход на следующий шаг алгоритма:

  1. проверка на доступность next-hop в локальной таблице маршрутизации. Если next-hop не доступен, маршрут отбрасывается.
  2. маршрутизатор выбирает маршрут с наибольшим Local Preference атрибутом.
  3. маршрутизатор выбирает маршрут с кратчайшим AS Path length.
  4. маршрутизатор выбирает маршрут с наименьшим значением атрибута Origin (то есть отдается предпочтение IGP).
  5. маршрутизатор выбирает маршрут с наименьшим значением MED. Этот шаг выполняется, по умолчанию, только для маршрутов из одной AS.
  6. маршрутизатор выбирает маршруты, полученные от соседей EBGP нежели полученные от IBGP соседей. Если остальные маршруты EBGP-маршруты, маршрутизатор переходит к шагу 9.
  7. маршрутизатор выбирает маршрут с наименьшей метрикой IGP к анонсируемому BGP Next Hop.
  8. если используется Route Reflection для IBGP пиринга, маршрутизатор выбирает путь с наименьшим Cluster-List length.
  9. маршрутизатор выбирает маршрут от партнера с наименьшим Router ID.
  10. маршрутизатор выбирает маршрут от партнера с наименьшим Peer Address.

BGP Session Establishment and Session States

Without any connection attemp, the session is firstly in the idle state. With the first TCP message, the state changes to connect.

bgp (border gataway protocol) session establishment
bgp (border gataway protocol) session establishment
 BGP Session EstablishmentFor BGP, firstly TCP connection must be established. This is called three-way handshake. This messages are SYN,SYN-ACK and ACK as you know.

After TCP connection, one peer send Open Message and the other peer respond with another Open Message. During this process the state become OpenSent .

You can test your BGP Knowledge on BGP Practice Tests Page!

Upon receipt of Open Messages, neighbours generates Keepalive Messages. The name of this state which one peer waiting the other for reply keepalive is OpenConfirm.

Lastly, after the receiving response keepalive, point-to-point connection is established.And the name of this last state is Established.

During this processes, if any IP connectivity problem occurs or any neighbour missconfiguraion or any other problem occurs, the state become Active. Do not think that this word is good for BGP. In BGP world, Active means there is a problem on connection.

bgp (border gataway protocol) session states summary
bgp (border gataway protocol) session states summary
BGP Session States SummaryIn BGP process, full routing table are sent to each neighbour after neighbourship. After this time, only incremental updates sent to each neighbour.

BGP keeps a version number of the BGP table. The version number changes whenever BGP updates the table with routing information changes.

BGP maintains a separate routing table based on shortest AS Path and various other Path Attributes, as opposed to IGP metrics like distance or cost. We will discuss these Path Attributes in the following posts.

AlphaPrep Practice Tests – Free Trial:

AlphaPrep Practice Tests - Free Trial

Типы сообщений

Заголовок BGP


Marker – содержит 1 в каждом бите, для совместимости с предыдущими версиями BGP.

Length – размер сообщения (включая заголовок) в байтах. 19 ≤ Length ≤ 4096.

Type – содержит код типа сообщения:

  1. OPEN

Сообщение OPEN

Используется для установки отношений соседства и обмена базовыми параметрами. Отправляется сразу после установки TCP-соединения.

Version(1)MyAutonomousSystem(2)—Hold-Time-(2)————BGP-Identifier-(4-байт)——— OptPLen(1)Optional-Parameters-(?)

Version – номер версии протокла

My Autonomous System – номер AS отправителя

Hold Time – макс. время в секундах, которое может пройти между получением KEEPALIVE и UPDATE

Optional Parameters Length – длина дополнительных параметров в байтах.

  • Если 0, то в Marker записываются единицы
  • Если не 0, то в Optional Parameters записываются данные для определения кода в Marker

Сообщение UPDATE

Используется для обмена информацией маршрутизации






Withdrawn Routes – список префиксов IP-адресов для отзываемых маршрутов.

Префикс = Длина, Префикс


Path Attributes – последовательность переменной длины с атрибутами пути.

Network Layer Reachability Information – последовательность переменной длины с адресными префиксами IP.

Префикс = Длина, Префикс

! Сообщение UPDATE может анонсировать не более одного набора атрибутов пути, но этому пути может соответствовать множество адресатов, путь к которым описывается общим набором атрибутов.


Используется, когда возникают ошибки BGP. После отправки сообщения, сессия с соседом разрывается.


Error Code – тип оповещения:

  1. Message Header Error
  2. OPEN Message Error
  3. UPDATE Message Error
  4. Hold Timer Expired
  5. Finite State Machine Error
  6. Cease


Используется для поддерживания отношений соседства, для обнаружения неактивных соседей.

Сообщения Keepalive состоят только из заголовка пакета.

Если периодичность отправки keepalive-сообщений равна 0, то сообщения не отправляются.


Решите Вашу проблему!