Tcpdump syntax error

PHP Code: sudo tcpdump -s 3600 -q -nxS -i en1 'ip and port 80' -w - | strin | The UNIX and Linux Forums

9 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

IF section problem. syntax error: unexpected end of file error

Hello,

I have another problem with my script. Please accept my apologies, but I am really nooby in sh scripts. I am writing it for first time.

My script:
returned=`tail -50 SapLogs.log | grep -i «Error»`
echo $returned
if ; then
echo «There is no errors in the logs»
fi

And after… (10 Replies)

Discussion started by: jedzio

2. Linux

Ambiguous redirect error and syntax error when using on multiple files

Hi,

I need help on following linux bash script. When I linux commands for loop or while loop on individual file it runs great. but now I want the script to run on N number of files so it gives me ambiguous redirect error on line 12 and syntax error on line 22 : (pls help );

#!/bin/bash
#… (16 Replies)

Discussion started by: Madhusudan Das

3. Shell Programming and Scripting

Receiving error: ./ang.ksh[35]: 0403-057 Syntax error at line 116 : `done’ is not expected.

Hi All
I am quite new to Unix. Following is a shell script that i have written and getting the subject mentioned error.
#!/bin/ksh
#————————————————————————-
# File: ang_stdnld.ksh
#
# Desc: UNIX shell script to extract Store information…. (3 Replies)

Discussion started by: amitsinha

5. Shell Programming and Scripting

sed error : Syntax error: redirection unexpected

My script is throwing the error ‘Syntax error: redirection unexpected’

My line of code..

cat nsstatustest.html | sed s/<tr><td align=»left»>/<tr><td align=»left» bgcolor=»#000000″><font color=»white»>/ > ztmp.Ps23zp2s.2-Fpps3-wmmm0dss3

HTML tags are getting in the way but they’re needed to… (3 Replies)

Discussion started by: phpfreak

6. AIX

nim mksysb error :/usr/bin/savevg[33]: 1016,07: syntax error

———————————————————————————

Hello, help me please.
I am trying to create a mksysb bakup using nim. I am geting this error, how to correct it ? :
Command : failed stdout: yes stderr: no… (9 Replies)

Discussion started by: astjen

7. UNIX for Dummies Questions & Answers

awk Shell Script error : «Syntax Error : `Split’ unexpected

hi there

i write one awk script file in shell programing
the code is related to dd/mm/yy to month, day year format

but i get an error

please can anybody help me out in this problem ??????

i give my code here including error

awk `
# date-month — convert mm/dd/yy to month day,… (2 Replies)

Discussion started by: Herry

8. IP Networking

tcpdump error: no suitable device found

Hi,

I’m trying to use tcpdump for the first time. I installed tcpdump from the rpm. Now when I issue the command tcpdump port 6666, I get an error

tcpdump: no suitable device found

Can you tell me what’s wrong there?

Thanks. (5 Replies)

Discussion started by: zampya

9. Programming

tcpdump error: no suitable device found

Hi,

I’m trying to use tcpdump for the first time. I installed tcpdump from the rpm. Now when I issue the command tcpdump port 6666, I get an error

tcpdump: no suitable device found

Can you tell me what’s wrong there?

Thank, (0 Replies)

Discussion started by: zampya

25.5.2 Фильтры tcpdump
На большинстве брандмауэров, tcpdump работающий без фильтров, будет производить такой объём вывода, что поиск интересуемого трафика станет трудным процессом. Существует множество выражений фильтрации, позволяющих вам ограничить отображаемый трафик или захватывать только интересуемый трафик.

25.5.2.1. Фильтры хоста
Для фильтрации специфического хоста, добавьте host и IP адрес к команде tcpdump. Для фильтрации хоста 192.168.1.100 вы должны выполнить следующую команду:

# tcpdump -ni em0 host 192.168.1.100

Это позволит захватывать весь трафик для и с этого хоста. Если вы хотите захватывать только трафик инициированный этим хостом, вы можете использовать директиву src.

# tcpdump -ni em0 src host 192.168.1.100

Аналогично, если вы хотите фильтровать трафик назначенный для этого IP адреса, вы должны указать директиву dst.

# tcpdump -ni em0 dst host 192.168.1.100

25.5.2.2. Сетевые фильтры
Сетевые фильтры позволяют сузить область захвата до указанной подсети, путём использования выражения net. Следом за net вы можете указать четырех значный (192.168.1.1), трехзначный (192.168.1), двухзначный (192.168) или однозначный (192) номер. Четырёхзначный номер эквивалентен указанию хоста, трехзначный использует маску подсети 255.255.255.0, двухзначный использует 255.255.0.0, а однозначный использует маску 255.0.0.0. Следующая команда отображает трафик для или с любого хоста с IP адресом 192.168.1.x.

# tcpdump -ni em0 net 192.168.1

Следующая команда в этом примере, будет захватывать трафик для или с хоста с IP адресом 10.x.x.x.

# tcpdump -ni em0 net 10

В этом примере будет захватываться весь трафик для или с специфической сети. Также, в можете указать src или dst, как и при использовании host, для фильтрации трафика по источнику или назначению указанной сети.

# tcpdump -ni em0 src net 10

Так же, в качестве аргумента net, возможно указать маску CIDR.

# tcpdump -ni em0 src net 172.16.0.0/12

25.5.2.3. Фильтры протокола и порта
Сужение обзора до хоста или сети, часто может оказаться недостаточным для устранения излишнего захвата трафика. Или, вы можете не озадачиваться источником и назначением, а просто хотите захватить определённый тип трафика. В любом случае, вы можете отфильтровать весь трафик опредлённого типа в целях снижения шума.

25.5.2.3.1. Фильтрация портов TCP и UDP
Для фильтрации по портам TCP и UDP, вы должны использовать директиву port. Это позволит захватывать трафик TCP и UDP использующий указанный порт в качестве порта назначения или источника. Для этого вы можете объединять директивы tcp или udp, в целях указания протокола, и src или dst для указания порта источника или назначения.

25.5.2.3.1.1. Захват всего трафика HTTP

# tcpdump -ni em0 tcp port 80

25.5.2.3.1.2. Захват всего трафика DNS
Захват всего трафика DNS (обычно UDP, однако некоторые запросы используют TCP)

# tcpdump -ni em0 port 53

25.5.2.3.2. Фильтры протокола
Вы можете фильтровать указанный протокол используя директиву proto. Протокол может быть указан с использованием номера IP проткола или как одно из имён: icmp, igmp, igrp, pim, ah, esp, vrrp, udp, или tcp. Указание vrrp также позволит захватывать трафик CARP т.к. он использует тот же самый номер IP протокола. Одно из общих использований директивы proto — фильтрация трафика CARP. Поскольку, нормальные имена протоколов являются зарезервированными словами, они должны быть экранированы одной или двумя обратными слешами, в зависимости от используемой оболочки. Оболочка используемая в pfSense требует использования двух обратных слешей для использования имён протоколов. Если вы получили синтаксическую ошибку, следует убедиться, что имя протокола экранировано правильно.
Следующий захват покажет весь трафик CARP и VRRP на интерфейсе em0, что может бть полезно для контроля отправляемых и получаемых данных по протоколу CARP на указанном интерфейсе.

# tcpdump -ni em0 proto \vrrp

25.5.2.4. Обратное соответствие фильтра
Помимо соответствия конкретных параметров, вы можете фильтровать несоответствующие параметры, указав not в начале выражения фильтрации. Если вы устраняете некоторую проблему отличную от CARP, а его вывод загромождает ваш захват, вы можете исключить его следующим образом:

# tcpdump -ni em0 not proto \vrrp

25.5.2.5. Комбинирование фильтров
Вы можете комбинировать любые из вышеупомянутых фильтров, используя and или or. Следующие разделы приводят несколько примеров.

25.5.2.5.1. Отображение всего трафика HTTP для и с хоста
Для отображения всего HTTP трафика хоста 192.168.1.11, используйте следующую команду.

# tcpdump -ni em0 host 192.168.1.11 and tcp port 80

25.5.2.5.2. Отображение всего трафика HTTP для и с нескольких хостов
Для отображения всего трафика HTTP с хостов 192.168.1.11 и 192.168.1.15, используйте следующую команду.

# tcpdump -ni em0 host 192.168.1.11 or host 192.168.1.15 and tcp port 80

25.5.2.6. Использование выражений фильтра
Выражения фильтра должны использоваться после каждого флага командной строки. Добавление любых флагов после выражения фильтра приводит к синтаксической ошибке.

25.5.2.6.1. Некорректный порядок

# tcpdump -ni en1 proto \vrrp -c 2
tcpdump: syntax error

25.5.2.6.2. Корректный порядок

# tcpdump -ni en1 -c 2 proto \vrrp
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on en1, link-type EN10MB (Ethernet), capture size 96 bytes
18:58:51.312287 IP 10.0.64.3 > 224.0.0.18: VRRPv2, Advertisement, vrid 4, pr
18:58:52.322430 IP 10.0.64.3 > 224.0.0.18: VRRPv2, Advertisement, vrid 4, pr
2 packets captured
80 packets received by filter
0 packets dropped by kernel

25.5.2.7. Больше о фильтрах
Этот раздел рассматривает только наиболее частое использование выражений фильтров в tcpdump, и вероятно весь необходимый вам синтаксис. Однако, это только поверхностное рассмотрение. В интернет доступно множество статей рассматривающих использование tcpdump в целом и фильтрации в частности. Обратитесь к разделу 25.8., «Дополнительные ссылки» в конце этой главы, где приведены дополнительные ссылки по данному вопросу.

продолжение следует…

Table of contents

IntroductionBACK TO TOC

In this article  I would like to talk about one of the most useful tools in my networking toolbox and that is tcpdump. Unfortunately mastering this tool completely is not an easy task. Yet stuff you do the most is relatively simple and may become a good springboard when diving into more complex topics.

tcpdump usesBACK TO TOC

tcpdump is a packet sniffer. It is able to capture traffic that passes through a machine. It operates on a packet level, meaning that it captures the actual packets that fly in and out of your computer. It can save the packets into a file. You can save whole packets or only the headers. Later you can “play” recorded file and apply different filters on the packets, telling tcpdump to ignore packets that you are not interested to see.

Under the hood, tcpdump understands protocols and host names. It will do all in its power to see what host sent each packet and will tell you its name instead of the IP address.

It is exceptionally useful tool for debugging what might have caused certain networking related problem. It is an excellent tool to learn new things.

InvocationBACK TO TOC

Invoking tcpdump is easy. First thing that you have to remember is that you should either be logged in as root or  be a sudoer on the computer – sudoer is someone who is entitled to gain administrator rights on computer for short period of time using sudo command.

Running tcpdump without any arguments makes it capture packets on first network interface (excluding lo) and print short description of each packet to output. This may cause a bit of a headache in case you are using network to connect to the machine. If you are connected with SSH or telnet (rlogin?), running tcpdump will produce a line of text for each incoming or outgoing packet. This line of text will cause SSH daemon to send a packet with this line, thus causing tcpdump to produce another line of text. And this will not stop until you do something about it.

Simple filteringBACK TO TOC

So first thing that we will learn about tcpdump is how to filter out SSH and telnet packets. We will study the basics of tcpdump filtering later in this guide, but for now just remember this syntax.

# tcpdump not port 22

“not port 22” is a filter specification that tells tcpdump to filter out packets with IP source or destination port 22. As you know port 22 is SSH port. Basically, when you tell tcpdump something like this, it will make tcpdump ignore all SSH packets – exactly what we needed.

Telnet on the other hand, uses port 23. So if you are connecting via telnet, you can filter that out with:

# tcpdump not port 23

Clear and simple!

Reading tcpdump‘s outputBACK TO TOC

By default tcpdump produces one line of text per every packet it intercepts. Each line starts with a time stamp. It tells you very precise time when packet arrived.

Next comes protocol name. Unfortunately, tcpdump understands very limited number of protocols. It won’t tell you the difference between packets belonging to HTTP and for instance FTP stream. Instead, it will mark such packets as IP packets. It does have some limited understanding of TCP. For instance it identifies TCP synchronization packets such as SYN, ACK, FIN and others. This information printed after source and destination IP addresses (if it IP packet).

Source and destination addresses follow protocol name. For IP packets, these are IP addresses. For other protocols, tcpdump does not print any identifiers unless explicitly asked to do so (see -e command line switch below).

Finally, tcpdump prints some information about the packet. For instance, it prints TCP sequence numbers, flags, ARP/ICMP commands, etc.

Here’s an example of typical tcpdump output.

17:50:03.089893 IP 69.61.72.101.www > 212.150.66.73.48777: P 1366488174:1366488582
(408) ack 2337505545 win 7240 <nop,nop,timestamp 1491222906 477679143>

This packet is part of HTTP data stream. You can see meaning of each and every field in the packet description in tcpdump’s manual page.

Here’s another example

17:50:00.718266 arp who-has 69.61.72.185 tell 69.61.72.1

This is ARP packet. It’s slightly more self explanatory than TCP packets. Again, to see exact meaning of each field in the packet description see tcpdump’s manual page.

Invocation continuedBACK TO TOC

Now, when we know how to invoke tcpdump even when connecting to the computer over some net, let’s see what command line switches are available for us.

Choosing an interfaceBACK TO TOC

We’ll start with a simple one. How to dump packets that arrived and sent through a certain network interface. -i command line argument does exactly this.

# tcpdump -i eth1

Will cause tcpdump to capture packets from network interface eth1. Or, considering our SSH/telnet experience:

# tcpdump -i eth1 not port 22

Finally, you can specify any as interface name, to tell tcpdump to listen to all interfaces.

# tcpdump -i any not port 22

Turning off name resolutionBACK TO TOC

As we debug networking issues, we may encounter a problem with how tcpdump works out of the box. The problem is that it tries to resolve every single IP address that it meets. I.e. when it sees an IP packet it asks DNS server for names of the computers behind IP address. It works flawlessly most of the time. However, there are two problems.

First, it slows down packet interception. It’s not a big deal when there are only few packets, but when there are thousands and tens of thousands it introduces a delay into the process. Amount of delay can be different, depending on the traffic.

Another, much more serious problem occurs when there is no DNS server around or when DNS server is not working properly. If this is the case, tcpdump spends few seconds trying to figure out two hostnames for each IP packet. This means virtually stopping intercepting the traffic.

Luckily there is a way around. There is an option that causes tcpdump to stop detecting hostnames and that is -n.

# tcpdump -n

And here are few variations of how you can use this option in conjunction with options that we have learned already.

# tcpdump -n -i eth1
# tcpdump -ni eth1 not port 22

Limiting number of packets to interceptBACK TO TOC

Here are few more useful options. Sometimes amount of traffic that goes in and out of your computer is very high, while all you want to see is just few packets. Often you want to see who sends you the traffic, but when you try to capture anything with tcpdump it dumps so many packets that you cannot understand anything. This is the case when -c command line switch becomes handy.

It tells tcpdump to limit number of packets it intercepts. You specify number of packets you want to see. tcpdump will capture that number of packets and exit. This is how you use it.

# tcpdump -c 10

Or with options that we’ve learned before.

# tcpdump -ni eth1 -c 10 not port 22

This will limit number of packets that tcpdump will receive to 10. Once received 10 packets, tcpdump will exit.

Saving captured dataBACK TO TOC

One of the most useful tcpdump features allows capturing incoming and outgoing packets into a file and then playing this file back. By the way, you can play this file not only with tcpdump, but also with WireShark (former Ethereal), the graphical packet analyzer.

You can do this with -w command line switch. It should be followed by the name of the file that will contain the packets. Like this:

# tcpdump -w file.cap

Or adding options that we’ve already seen

# tcpdump -ni eth1 -w file.cap not port 22

Changing packet size in the capture fileBACK TO TOC

By default, when capturing packets into a file, it will save only 68 bytes of the data from each packet. Rest of the information will be thrown away.

One of the things I do often when capturing traffic into a file, is to change the saved packet size. The thing is that disk space that is required to save the those few bytes is very cheap and available most of the time. Spending few spare megabytes of your disk space on capture isn’t too painful. On the other hand, loosing valuable portion of packets might be very critical.

So, what I usually do when capturing into a file is running tcpdump with -s command line switch. It tells tcpdump how many bytes for each packet to save. Specifying 0 as a packet’s snapshot length tells tcpdump to save whole packet. Here how it works:

# tcpdump -w file.cap -s 0

And with conjunction with options that we already saw:

# tcpdump -ni eth1 -w file.cap -s 0 -c 1000 not port 22

Obviously you can save as much data as you want. Specifying 1000 bytes will do the job for you. Just keep in mind that there are so called jumbo frames those size can be as big as 8Kb.

Reading from capture fileBACK TO TOC

Now, when we have captured some traffic into a file, we would like to play it back. -r command like switch tells tcpdump that it should read the data from a file, instead of capturing packets from interfaces. This is how it works.

# tcpdump -r file.cap

With capture file, we can easily analyze the packets and understand what’s inside. tcpdump introduces several options that will help us with this task. Lets see few of them.

Looking into packetsBACK TO TOC

There are several options that allow one to see more information about the packet. There is a problem though. tcpdump in general isn’t giving you too much information about packets. It doesn’t understand different protocols.

If you want to see packet’s content, it is better to use tools like Wireshark. It does understand protocols, analyzes them and allows you to see different fields, not only in TCP header, but in layer 7 protocols headers.

tcpdump is a command line tool and as most of the command line tools, its ability to present information is quiet limited. Yet, it still has few options that control the way packets presented.

Seeing Ethernet header for each packetBACK TO TOC

-e command line switch, causes tcpdump to present Ethernet (link level protocol) header for each printed packet. Lets see an example.

# tcpdump -e -n not port 22

Controlling time stampBACK TO TOC

There are four command line switches that control the way how tcpdump prints time stamp. First, there is -t option. It makes tcpdump not to print time stamps. Next comes -tt. It causes tcpdump to print time stamp as number of seconds since Jan. 1st 1970 and a fraction of a second. -ttt prints the delta between this line and a previous one. Finally, -tttt causes tcpdump to print time stamp in it’s regular format preceeded by date.

Controlling verbosityBACK TO TOC

-v causes tcpdump to print more information about each packet. With -vv tcpdump prints even more information. As you could guess, -vvv produces even more information. Finally -vvvv will produce an error message telling you there is no such option :D

Printing content of the packetBACK TO TOC

-x command line switch will make tcpdump to print each packet in hexadecimal format. Number of bytes that will be printed remains somewhat a mystery. As is, it will print first 82 bytes of the packet, excluding ethernet header. You can control number of bytes printed using -s command line switch.

In case you want to see ethernet header as well, use -xx. It will cause tcpdump to print extra 14 bytes for ethernet header.

Similarily -X and -XX will print contents of packet in hexadecimal and ASCII formats. The later will cause tcpdump to include ethernet header into printout.

Packet filteringBACK TO TOC

We already saw a simple filter. It causes tcpdump to ignore SSH packets, allowing us to run tcpdump from remote. Now lets try to understand the language that tcpdump uses to evaluate filter expressions.

Packet matchingBACK TO TOC

We should understand that tcpdump applies our filter on every single incoming and outgoing packet. If packet matches the filter, tcpdump aknownledges the packet and depending on command line switches either saves it to file or dumps it to the screen. Otherwise, tcpdump will ignore the packet and account it only when telling how many packets received, dropped and filtered out when it exits.

To demostrate this, lets go back to not port 22 expression. tcpdump ignores packets that either sourced or destined to port 22. When such packet arrives, tcpdump applies filter on it and since the result is false, it will drop the packet.

More qualifiersBACK TO TOC

So, from what we’ve seen so far, we can conclude that tcpdump understands a word port and understands expression negation with not. Actually, negating an expression is part of complex expressions syntax and we will talk about complex expressions a little later. In the meantime, lets see few more packet qualifiers that we can use in tcpdump expressions.

We’ve seen that port qualifier specifies either source or destination port number. In case we want to specify only the source port or only the destination port we can use src port or dst port. For instance, using following expression we can see all outgoing HTTP packets.

# tcpdump -n dst port 80

We can also specify ranges of ports. portrange, src portrange and dst portrange qualifiers do exactly this. For instance, lets see a command that captures all telnet and SSH packets.

# tcpdump -n portrange 22-23

Specifying addressesBACK TO TOC

Using dst host, src host and host qualifiers you can specify source, destination or any of them IP addresses. For example

# tcpdump src host alexandersandler.net

Will print all packets originating from alexandersandler.net computer.

You can also specify Ethernet addresses. You do that with ether src, ether dst and ether host qualifiers. Each should be followed by MAC address of either source, destination or source or destination machines.

You can specify networks as well. The net, src net and dst net qualifiers do exactly this. Their syntax however slighly more complex than those of a single host. This is due to a netmask that has to be specified.

You can use two basic forms of network specifications. One using netmask and the other so called CIDR notation. Here are few examples.

# tcpdump src net 67.207.148.0 mask 255.255.255.0

Or same command using CIDR notation.

# tcpdump src net 67.207.148.0/24

Note the word mask that does the job of specifying the network in first example. Second example is much shorter.

Other qualifiersBACK TO TOC

There are several useful qualifiers that don’t fall under any of the categories I already covered.

For instance, you can specify that you are interested in packets with specific length. length qualifier does this. less and greater qualifiers tell tcpdump that you are interested in packets whose length is less or greater than value you specified.

Here’s an example that demonstrates these qualifiers in use.

# tcpdump -ni eth1 greater 1000

Will capture only packets whose size is greater than 1000 bytes.

Complex filter expressionsBACK TO TOC

As we already saw we can build more complex filter expressions using tcpdump filters language. Actually, tcpdump allows exceptionally complex filtering expressions.

We’ve seen not port 22 expression. Applying this expression on certain packet will produce logical true for packets that are not sourced or destined to port 22. Or in two words, not negates the expression.

In addition to expression negation, we can build more complex expressions combining two smaller expression into one large using and and or keywords. In addition, you can use brackets to group several expressions together.

For example, lets see a tcpdump filter that causes tcpdump to capture packets larger then 100 bytes originating from google.com or from microsoft.com.

# tcpdump -XX greater 100 and (src host google.com or src host microsoft.com)

and and or keywords in tcpdump filter language have same precedence and evaluated left to right. This means that without brackets, tcpdump could have captured packets from microsoft.com disregarding packet size. With brackets, tcpdump first makes sure that all packets are greater than 100 bytes and only then checks their origin.

Note the backslash symbol (“”) before brackets. We have to place them before brackets because of shell. Unix shell has special understanding of what brackets used for. Hence we have to tell shell to leave these particular brackets alone and pass them as they are to tcpdump. Backslash characters do exactly this.

Talking about precedence, we have to keep in mind that in tcpdump’s filter expression language not has higher precedence than and and or. tcpdump’s manual page has very nice example and emphasizes the meaning of this.

not host vs and host ace

and

not (host vs or host ace)

are two different expressions. Because not has higher precedence over and and or, filter from the first example will capture packets not to/from vs, but to/from ace. Second filter example on the other hand will capture packets that are not to/from vs and to/from ace. I.e. first will capture packet from ace to some other host (but not to vs). Yet second example won’t capture this packet.

Repeating qualifiersBACK TO TOC

To conclude this article, I would like to tell you one more thing that may become handy when writing complex tcpdump filter expressions.

Take a look at the following example.

# tcpdump -XX greater 100 and (src host google.com or microsoft.com)

We already saw this example, with one little exception. In previous example we had a src host qualifier before microsoft.com and now its gone. The thing is that if we want to use same qualifier two times in a row, we don’t have to specify it twice. Instead we can just write qualifier’s parameter and tcpdump will know what to do.

This makes tcpdump filter expression language much easier to understand and much more readable.

AfterwordBACK TO TOC

I hope you found this article useful. In case you have questions, suggestions or you would like to share your appreciation to the author ;-) , don’t hesitate to mail me to alexander.sandler@gmail.com

Tcpdump with no filters will produce so much output that it will prove very difficult to find traffic of interest. There are numerous filtering expressions available that limit the traffic displayed or captured.

  • Host filters
  • Network filters
  • Port filters
  • Protocol filters
  • Negating a filter match
  • Combining filters

Host filters

To filter for a specific host, append host and the IP address to the tcpdump command. To filter for host 192.168.1.100 use the following command:

# tcpdump -ni igb1 host 192.168.1.100

That will capture all traffic to and from that host. To only capture traffic being initiated by that host, use the src directive:

# tcpdump -ni igb1 src host 192.168.1.100

Similarly, filtering for traffic destined to that IP address is possible by specifying dst:

# tcpdump -ni igb1 dst host 192.168.1.100

Network filters

Network filters narrow the capture to a specific subnet using the net expression. Following net, specify a dotted quad ( 192.168.1.1), dotted triple ( 192.168.1), dotted pair (192.168) or simply a number ( 192).

A dotted quad is equivalent to specifying host, a dotted triple uses a subnet mask of 255.255.255.0, a dotted pair uses 255.255.0.0, and a number alone uses 255.0.0.0.

The following command displays traffic to or from any host with a 192.168.1.x IP address:

# tcpdump -ni igb1 net 192.168.1

The next command will capture traffic to or from any host with a 10.x.x.x IP address:

# tcpdump -ni igb1 net 10

Those examples will capture all traffic to or from the specified network. The src or dst keywords may be used the same as with host filters to capture only traffic initiated by or destined to the specified network:

# tcpdump -ni igb1 src net 10

A CIDR mask can also be passed as an argument to net:

# tcpdump -ni igb1 src net 172.16.0.0/12

Port filters

Narrowing down by host or network frequently isn’t adequate to eliminate unnecessary traffic from a capture. Or the source or destination of traffic may not be significant, and all traffic of a certain type should be captured. In other cases, filtering out all traffic of a specific type can reduce noise.

To filter on TCP and UDP ports, use the port directive. This captures both TCP and UDP traffic using the specified port either as a source or destination port. It can be combined with tcp or udp to specify the protocol, and src or dst to specify a source or destination port.

  • Capture all HTTP traffic # tcpdump -ni igb1 tcp port 80
  • Capture all DNS traffic (usually UDP, but some queries use TCP): # tcpdump -ni igb1 port 53

Protocol filters

Specific protocols can be filtered using the proto directive or by using the protocol name directly.

The following capture will show all ICMP traffic on the igb1 interface:

# tcpdump -ni igb1 icmp

Negating a filter match

In addition to matching specific parameters, a filter match can be negated by specifying not in front of the filter expression. When troubleshooting something other than icmp, exclude it as follows:

# tcpdump -ni igb1 not icmp

Combining filters

Any of the aforementioned filters can be combined using and or or. The following sections provide some examples.

  • Display all HTTP traffic to and from a host
  • Display all HTTP traffic to or from 192.168.1.11:
  • # tcpdump -ni igb1 host 192.168.1.11 and tcp port 80
  • Display all HTTP traffic to and from multiple hosts
  • Display all HTTP traffic from either 192.168.1.11 or 192.168.1.15:
  • # tcpdump -ni igb1 host 192.168.1.11 or host 192.168.1.15 and tcp port 80

Filter expression usage

Filter expressions must come after every command-line flag used. Adding any flags after a filter expression will result in a syntax error.

  • Incorrect ordering
  • # tcpdump -ni igb1 -T carp carp -c 2
  • tcpdump: syntax error
  • Correct ordering
  • # tcpdump -ni igb1 -T carp -c 2 carp

tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on igb1, link-type EN10MB (Ethernet), capture size 65535 bytes
14:50:07.426993 IP 198.51.100.12 > 224.0.0.18: CARPv2-advertise 36: vhid=11 advbase=1 advskew=0 authlen=7 counter=5449924379588860810
14:50:08.436849 IP 198.51.100.12 > 224.0.0.18: CARPv2-advertise 36: vhid=11 advbase=1 advskew=0 authlen=7 counter=5449924379588860810
2 packets captured
78 packets received by filter
0 packets dropped by kernel

Понравилась статья? Поделить с друзьями:
  • Technical error please try again later перевод
  • Tcpdf error some data has already been output can t send pdf file
  • Tcpdf error please explicitly set action attribute path
  • Tcpdf error image unable to get the size of the image
  • Tcp socket read operation failed error 64