Send udp packets linux

Send and Receive UDP packets via Linux CLI

Expectations:

Here are the key points to learn from this article

  1. To understand nc command in Linux.
  2. Use nc command for sending and receiving UDP packets through network.
  3. Send some human readable sentences through nc command.
  4. Capture the UDP packet sent by nc command.
  5. Check network packet in Wireshark.
  6. Find out any other command other than netcat for Linux.

Netcat Command:

Netcat(nc) command is installed by default in Linux OS. Open one terminal [Shortcut Alt+Ctrl+t] and use below command to check if nc is present or not.

Here is the expected output

This is nc from the netcat-openbsd package. An alternative nc is available
in the netcat-traditional package.

usage: nc [-46bCDdhjklnrStUuvZz] [-I length] [-i interval] [-O length]
[-P proxy_username] [-p source_port] [-q seconds] [-s source]
[-T toskeyword] [-V rtable] [-w timeout] [-X proxy_protocol]
[-x proxy_address[:port]] [destination] [port]

This means nc command is already exist in Linux.

General Set Up Diagram:

Send UDP packet:

Let’s take an example like we will send UDP packet from System A to System B. So, in server-client concept, we have to run server at System B side and client at System A side.

Also we have valid IP addresses.

Start Server:

To start sever using nc command use below command in System B terminal

Here is the screenshot

This command does not have any output to show as of now. This is just listening mode on port 9999.

Start Client:

To connect to server using nc command use below command in System A terminal

Now system A has to connect to System B. So we have provided server IP address and port number.

Here is the screenshot

Check Connection:

We can check the below command for the confirmation about client connation to server port.

Here is the screenshot

Send UDP packets:

Now we can send udp packet from System A to B and vice versa.

Step 1:

Now go to system A and send any sentences like

Step 2:

We should able to see this in System B side. Here is the screenshot

We can also send UDP packets from System B to System A.

Step 1:

Go to System B and send sentence like

Here is the screenshot from System B

Step 2:

Here is the screenshot from System A

Check packets in Wireshark:

Now while we have been sending UDP packets from System A to System B and vice verse, we can start Wireshark in either System A or System B. Here we have the capture file, let’s do some analysis and confirm if this server and client communication used UDP protocol.

Note that we will only analyze the first communication:

System A has sent:

To:

We will use filter “udp.port == 9999” to get only related packets in Wireshark. Refer below screenshot for analysis from Wireshark capture:

To know how to use Wireshark refer below link

Other command to send UDP packets:

There is another method to send UDP packets

Run server at System B:

Run below command at System A:

But we are able to send only one time “hello”. If we kill server and rerun then it’s working.

Conclusion:

From the above exercise we have learned the mechanism to send some messages using UDP protocol. And the best method is to use nc command in Linux.

Источник

unakatsuo / raw_udp4.go

// +build linux
package main
import (
«fmt»
«net»
«os»
«syscall»
«github.com/google/gopacket»
«github.com/google/gopacket/layers»
)
// This example sends an UDP packet to 127.0.0.1:5000 using Linux raw socket. This program needs root priviledge or CAP_NET_RAW capability.
// Run «nc -ul 127.0.0.1 5000» to see the «HELLO» message in the payload.
// http://www.pdbuchan.com/rawsock/rawsock.html
func open ( ifName string ) (net. PacketConn , error ) <
fd , err := syscall . Socket ( syscall . AF_INET , syscall . SOCK_RAW , syscall . IPPROTO_RAW )
if err != nil <
return nil , fmt . Errorf ( «Failed open socket(syscall.AF_INET, syscall.SOCK_RAW, syscall.IPPROTO_RAW): %s» , err )
>
syscall . SetsockoptInt ( fd , syscall . IPPROTO_IP , syscall . IP_HDRINCL , 1 )
if ifName != «» <
iface , err := net . InterfaceByName ( ifName )
if err != nil <
return nil , fmt . Errorf ( «Failed to find interface: %s: %s» , ifName , err )
>
syscall . SetsockoptString ( fd , syscall . SOL_SOCKET , syscall . SO_BINDTODEVICE , ifName )
>
conn , err := net . FilePacketConn ( os . NewFile ( uintptr ( fd ), fmt . Sprintf ( «fd %d» , fd )))
if err != nil <
return nil , err
>
return conn , nil
>
func buildUDPPacket ( dst , src * net. UDPAddr ) ([] byte , error ) <
buffer := gopacket . NewSerializeBuffer ()
payload := gopacket . Payload ( «HELLO» )
ip := & layers. IPv4 <
DstIP : dst . IP ,
SrcIP : src . IP ,
Version : 4 ,
TTL : 64 ,
Protocol : layers . IPProtocolUDP ,
>
udp := & layers. UDP <
SrcPort : layers . UDPPort ( src . Port ),
DstPort : layers . UDPPort ( dst . Port ),
>
if err := udp . SetNetworkLayerForChecksum ( ip ); err != nil <
return nil , fmt . Errorf ( «Failed calc checksum: %s» , err )
>
if err := gopacket . SerializeLayers ( buffer , gopacket. SerializeOptions < ComputeChecksums : true , FixLengths : true >, ip , udp , payload ); err != nil <
return nil , fmt . Errorf ( «Failed serialize packet: %s» , err )
>
return buffer . Bytes (), nil
>
func main () <
conn , err := open ( «lo» )
if err != nil <
panic ( err )
>
dst := & net. UDPAddr <
IP : net . ParseIP ( «127.0.0.1» ),
Port : 5000 ,
>
b , err := buildUDPPacket ( dst , & net. UDPAddr < IP : net . ParseIP ( "127.0.0.1" ), Port : 5001 >)
if err != nil <
panic ( err )
>
wlen , err := conn . WriteTo ( b , & net. IPAddr < IP : dst . IP >)
if err != nil <
panic ( err )
>
fmt . Printf ( «Sent IP packet %d bytes to %s \n » , wlen , dst )
>

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

Sending TCP/UDP packets using Netcat

There are a number of protocols powering the Internet of Things. Choosing the right one will depend on your project’s security, bandwidth and reliability needs, or maybe just your device computing limitations. In some cases like cellular transmission, the good old TCP/UDP packet transmission will work just fine. This article will show you how to simulate a client using a useful tool called Netcat and realize the immediate connection using your own computer’s terminal.

Читайте также:  Как открыть порт linux centos

To learn how to send data to Ubidots using these protocols, see Send Data to Ubidots over TCP or UDP.

Netcat is a featured networking utility which reads and writes data across network connections, using the TCP/IP protocol. Designed to be a reliable «back-end» tool, Netcat can be used directly with other programs and scripts to send files from a client to a server and back. At the same time, it is a feature-rich network debugging and exploration tool that can specify the network patameters while also establishing a connection to a remote host via a tunnel.

Although Netcat can do many things, its main purpose and most desirable function is to:

Create an initial socket to establish a connection from server to the client.

Once connected, Netcat will automatically generate a second socket to transmit files from the server to the client and visa versa. (This is the really cool part.)

Reference below for a diagram of the data Netcat protocol architecture.

Something so simple happens to be extraordinarily powerful and flexible as you will see below. For simplicity, local connections are used, although, of course, they can be used between different machines.

Syntax

nc [-options] hostname port[s] [ports]
nc -l -p port [-options] [hostname] [port]

Basic parameters

l: set the «listen» mode, waits for the incoming connections.

u: set the UDP mode

Test your Netcat understanding as a client-server

Open two computer terminals, the first will act as the server and the second will be the client.

TCP client

With Netcat your PC can be converted in a server, you want to begin as a server that listens at port 2399:

In addition, we can use the server to connect to the port (2399) recently opened, from the client side:

As you can see on the image below, the connection is established:

With the connection established you are now able to write to the server from the client:

In the terminal where the server is running, your text files will appear seamlessly.

UDP client

By default Netcat uses the TCP protocol for its communications, but it can also UDP using the -u option.

As we mentioned at the previous step, Netcat lets you convert your PC in a server. In this case we’re going to establish the connection between the server and the client but using UDP.

From the server side, run the command below. As you can see, the command establishes the UDP connection just requires the -u to be added to the command:

Once you start the server, establish the connection with the client:

Now the client and the server are using UDP protocol for their communication. You can verify commincation using the netstat command in a new (3rd) computer terminal.

$ netstat | grep 2399
udp 0 0 localhost:2399 localhost:57508 ESTABLISHED

As you can see in the images below, the message is received by the server, and the transmission is verified by the connection:

With this introduction to Netcat, you now have a better understanding of this advanced tool to send data quickly and efficiently between client and server. For additional information, check out this link.

This article was originally published on Ubidots’ Blog on June 22, 2017.

Источник

Send udp packets linux

Packet Sender is an open source utility to allow sending and receiving TCP, UDP, and SSL (encrypted TCP) packets. The mainline branch officially supports Windows, Mac, and Desktop Linux (with Qt). Other places may recompile and redistribute Packet Sender. Packet Sender is free and licensed GPL v2 or later. It can be used for both commercial and personal use.

Packet Sender would like to thank the following sponsors.

IWL is a California company creating computer networking products.

NagleCode is a software publisher and development studio. NagleCode licenses the mobile apps.

JetBrains provides world-class programming tools to help speed development.

GitHub provides repositories, downloads, and issue tracking for any code project.

  • Twitter: @NagleCode
  • Forums are at: GitHub Discussions.
  • Email: Packet Sender Contact
  • Connect with me on LinkedIn

NOTE: Try (temporarily) disabling your firewall if having problems in Windows.

  • Controlling network-based devices in ways beyond their original apps
  • Test automation (using its command line tool and/or hotkeys)
  • Testing network APIs (using the built-in TCP, UDP, SSL clients)
  • Malware analysis (using the built-in UDP, TCP, SSL servers)
  • Troubleshooting secure connections (using SSL ).
  • Testing network connectivity/firewalls (by having 2 Packet Senders talk to each other)
  • Stress-testing a device (using intense network generator tool)
  • Tech support (by sending customers a portable Packet Sender with pre-defined settings and packets)
  • Sharing/Saving/Collaboration using the Packet Sender Cloud service.

Official releases of Packet Sender can be downloaded at PacketSender.com. Some places redistribute Packet Sender.

The Packet Sender mobile editions are fully native, contain bare minimum permissions, and collects no data. This is software that respsects you. Thank you for supporting this effort.

The Android version is located on Google Play or on Amazon Appstore

The iOS version is located on the Apple App Store

Packet Sender Cloud

Packets sets can be quickly saved/retrieved/shared using the free Packet Sender Cloud service. The cloud may also be used to publicly display and distribute your packets (via an URL) for collaboration, tutorials, end users, etc. Packet Sender may import public packet sets with public URL.

There are various reasons to do this:

  • Keeping all your packets ready so you can quickly retrieve them when installing a fresh Packet Sender
  • Quickly swapping between packet sets when working on different projects.
  • Sharing a login (it is allowed) for collaborative packet set generation
  • Having a public page of your packet sets so others can quickly find and import

If you are publishing a network API, maintaining a public cloud page is significantly easier than painfully detailing (IP, port, type, etc) the packets to your users. Plus, updating that page is easy.

More information about it can be found at https://cloud.packetsender.com/help

Читайте также:  Hp bang olufsen audio module windows 10

Packet Sender has a «portable» mode. At launch, it will look for packets.ini and ps_settings.ini in its run-time directory. For the SSL server, it will look for ps.key and ps.pem .

Windows users, this directory is the same place as the .exe. For Mac users, this run-time directory is at PacketSender.app/Contents/MacOS . If INI files are found, it will use them instead of %APPDATA% or Library/Application Support .

IPv4, IPv6, and Custom IP

Packet Sender’s built-in servers are configured to support either IPv4 or IPv6 but not both at the same time. For clients, Packet Sender GUI and CLI will seemlessly switch between the two modes upon sending (you may need to include the scope ID). Older versions of Packet Sender tried use both simultaneously, but testing found this unreliable. Click the IPv4 / IPv6 toggle on the bottom right to switch between the two.

Inside the settings, you may also force Packet Sender’s servers to bind to a custom IP address. This can be very useful for systems with multiple NICs or complicated IP setups. Packet Sender will trigger an error if told to bind to an address that does not exist.

Packet Sender’s multicast support is triggered by attempting to send to a IPv4 multicast address or via the mulitcast submenu). The feature is currently experimental and has these known problems.

  • Packet Sender abandons IPv6 support when joining multicast.
  • And stays abandoned until you revisit settings or attempt to send to IPv6
  • On wifi, it sometimes takes 20 seconds for multicast join to actually take effect.
  • Packet Sender has no logic to rejoin a mulitcast group if the switch reboots or some other common error.

There is no IPv6 multicast support, though it is on the roadmap. Sponsors wanting IPv6 multicast support are welcome to contact me.

UDP Traffic Generator (Experimental)

For when the normal send system is not enough, you can now hammer a target IP with packets to see if your device can handle it. Please note that this feature is experimental and the metrics displayed have not been fully tested.

Additional Documentation (GUI)

Packet Sender is identical for all the desktop versions. The only difference is its theme to match the operating system.

  • In the bottom right, there are UDP, TCP, and SSL server status and port(s). You can click to activate or deactivate these. Packet Sender supports binding to any number of ports.
  • There is also IPv4 (default), IPv6, custom IP, toggle button
  • During packet resending, there will be a button to cancel all resends.
  • Please check your firewall. Windows aggressively blocks TCP-based servers. Packet Sender will still work if the firewall blocks it, but it can’t receive unsolicited TCP-based packets.
  • In the table, there is a list of saved packets. You can double-click to directly edit fields in this table.
  • Select multiple packets to enable «Multi-Send». Selected packets are shown in a quick-send area above the traffic log.
  • Fields can be rearranged by drag-and-drop in the settings menu.
  • A resend value of «0» means it is a single-shot packet.
  • A packet has a name, destination address (domain names are default resolved just before sending), port, and data associated with it.
  • Click «Send» to immediately send. Click «Save» to send later.
  • For IPv6 sending, you will also need the scope ID.
  • Packet Sender supports mixed ASCII and HEX notation:
    • \XX gets translated to XX in hex
    • \n, \r, \t will get translated to 0A, 0D, and 09
    • HEX numbers are space delimited
      • The HEX field will attempt to interpret other common delimiters (such as commas, colons (Wireshark), semicolons, » 0x», etc) and auto-correct.
      • A single stream of HEX is also supported. If the number of bytes is odd, Packet Sender will assume the front byte needs a zero and then auto-correct.
    • Example ASCII: hello world\r
    • Example HEX: 68 65 6c 6c 6f 20 77 6f 72 6c 64 0d
    • You may save a packet directly from the traffic log. You will be prompted for a name, and the source address and port will be switched for your convenience.
    • You may also load a file directly in to the HEX field. The HEX field supports sending up to 10,922 bytes. The theoretical limit for sending via the command line is 200 MB.
  • An optional response can be sent. The same response is used for TCP and UDP.

Hotkeys / Keyboard Shortcuts

The fields at the top can be navigated using CTRL+1, CTRL+2, etc, up to CTRL+8 (send button). On Mac, the shortcut key is Command.

  • When you navigate to the TCP/UDP/SSL option, you may use up/down or t/u/s characters.
  • If you are going to automate with hotkeys (using tools such at AutoHotKey), you may want to turn off «Restore previous session».

SSL Client and Server

Packet Sender supports establishing encrypted connections over SSL. This is supported in the GUI and on the command line. Some notes on this:

  • The certificate negotiation is handled immediately during connection.
  • By default, Packet Sender ignores all SSL errors (expired cert, wrong host name, self-signed, etc).
  • Packet Sender outputs the cert negotiation progress in to the traffic log.
  • Packet Sender outputs the encryption algorithm used in the traffic log (such as AES 128).

Packet Sender bundles an internal «Snake Oil» certificate for use as a server for Windows. The certificate and key is in the same place as packet and settings.

  • Overriding the cert locations in Settings also overrides these snake-oil certificate.

Packet Sender bundles OpenSSL for use in Windows. On Mac and Linux, Packet Sender will use the native SSL libraries.

This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit. (http://www.openssl.org/)

  • If there is an SSL error, Packet Sender will output it to the traffic log. If the setting is to continue anyway (default), it will continue to negotiate encryption. Otherwise, the connection ends with failure to connect.

Packet Sender supports up to 5 smart responses. To use it, disable normal responses.

  • Packet Sender will compare the packet within the encoding you choose.
  • Packet Sender translates the encoding before sending out the reply.
  • The available encodings are:
    • Mixed ASCII — The standard Packet Sender way of encoding ASCII along with non-printable characters
    • HEX — Packet Sender’s normal HEX encoding
    • EBCDIC (deprecated) — An encoding used mostly by IBM mainframes. The input field is normal Mixed ASCII and is translated when performing the comparison and sending.
Читайте также:  Сколько озу использует windows 10 x64

Packet Sender supports these macros when sending responses:

  • <> — Sends the current date in «yyy-mm-dd» format.
  • <
  • <> — Sends the current epoch time stamp.
  • <> — Sends a random number ranging from either 0 to 32767 or 2147483647, depending on 32-bit or 64-bit (default installer for Windows is 32-bit. Mac is 64-bit).
  • <> — Sends a random string. Uses an internal UUID to generate it. Packet Sender will swap the macro with real values before sending.

Persistent TCP and SSL

Packet Sender supports persistent TCP and SSL connections via a separate UI dialog. It is enabled by checkbox on the main window or in the settings dialog.

  • Any number of persistent connections can be created.
  • Previously saved packets can be loaded in the drop-down.
  • There is a «raw» view and «ASCII» view. The ASCII view is useful to troubleshoot data that is not printed by the raw view.
  • Traffic is also saved in the main window traffic log.
  • A file may be uploaded to the persistent connection. You may wish to turn off logging if you use this.
  • The timer in the bottom lefts starts as soon as a valid data packet is sent/received. It stops when the connection is closed.
  • You may optionally append a carriage return when you quick-send by hitting the return key. This is useful for command-prompt menus over TCP / SSL connections. Packet Sender remembers previous state of \r checkbox.
  • Incoming persistent connections to the server will launch the UI dialog.
  • During resend, the persistent connection packet is carried over to the new UI dialog. Clicking «Resending(1)» will cancel it.

Persistent connections are not supported via the command line.

IPv4 Subnet Calculator

Packet Sender has a built-in subnet calculator. It is under the Tools menu.

  • The log window will display non-loopback IPv4 and IPv6 addresses found on your computer.
  • The top left field allow inputting an IPv4 address.
  • The field below is for a subnet, either X.X.X.X or /XX notation.
  • The results of the calculation are on the right.
  • The field below is a quick check to see if an IPv4 is within one of your subnets.

Additional Configuration Options

  • IPv4 Mode, IPv6 Mode, Custom IP in the servers. This is identical to the toggle switch except toggle switch does not remember custom IP.
  • The traffic log and packet table is divided by a draggable splitter. This splitter can also be collapsed on either side.
  • Copy to the clipboard the raw packet data (default). If your data has a large amount of non-ASCII characters, you may prefer a translated version.
  • Resending can be auto-cancelled after X number of packets. Set to 0 to resend forever.
  • Traffic log can be set to roll at 100 entries. Otherwise, the log rolls at 10k.
  • Import/Export of packets is available via menus.
  • Attempt receive before send (some servers expect this behavior).
  • 500 ms delay before sending data (some servers are slow).
  • Enable keyboard shortcut for ASCII —> EBCDIC translation (deprecated).
  • Resolve DNS during input. The default is to resolve DNS just before sending.
  • Ignore SSL errors. Packet Sender will note the error and continue with encryption. Otherwise, Packet Sender abandons the connection. The SSL server always ignores errors.

Documentation (Command Line)

The command line extension used in Windows installations is .com. Using .exe will launch the GUI. Leave off the extension and Windows will choose the correct program. The same executable controls the command line and GUI for Mac and Linux operating systems.

The command line system in Packet Sender follows the same pattern as other Linux utilities. It has a long name (such as —version) and a short name (such as -v). These options can be arranged in any order and Packet Sender will parse them correctly. The last 3 options are positional and must appear last. They are IP, port, and data. These last options are optional if using a stored packet.

Send contents of specified path. Max 10 MiB for UDP, 100 MiB for TCP/SSL. -b, —bind

Bind port. Default is 0 (dynamic). -6, —ipv6 Force IPv6. Same as -B «::». Default is IP:Any. -4, —ipv4 Force IPv4. Same as -B «0.0.0.0». Default is IP:Any. -B, —bindip Bind custom IP. Default is IP:Any. -t, —tcp Send TCP (default). -s, —ssl Send SSL and ignore errors. -S, —SSL Send SSL and stop for errors. -u, —udp Send UDP. -n, —name Send previously saved packet named . Other options overrides saved packet parameters. Arguments: address Destination address. Optional for saved packet. port Destination port. Optional for saved packet. data Data to send. Optional for saved packet. «>

Examples binding to port and custom IP, IPv4, or IPv6

Packet Sender command line can bind to custom ports to force IPv4/6 modes or multiple NIC.

Example CLI using SSL and ignoring errors

The command line has the option to ignore or abandon on SSL errors. The default is to ignore.

Building Packet Sender

The only dependency is Qt SDK. Here is how to build the app.

Build for Windows and Mac

  1. Download the Qt installer from http://www.qt.io/download-open-source/
  2. Let it install MingGW if you don’t have a compiler.
  3. Open the project PacketSender.pro
  4. Build! Qt is the only dependency!

The Windows and Mac versions were built using Qt 5.12

Build for Linux

Here is the sequence of commands for Ubuntu 16.04. Please adapt to your Linux platform. Packet Sender requires no additional libraries beyond the stock Qt SDK. I have been told there are build issues with stock Fedora. If a Fedora wizard has insight, please let me know, and I’ll add your instructions.

If you are feeling adventurous, feel free to build from the master branch. It contains the latest stable build. The development branch should probably be avoided.

If it doesn’t run, you may need to set it executable

Источник

Оцените статью