Linux send udp message

Полезные трюки при работе с netcat

В данной статье я рассмотрю популярную сетевую утилиту netcat и полезные трюки при работе с ней.

Netcat — утилита Unix, позволяющая устанавливать соединения TCP и UDP, принимать оттуда данные и передавать их. Несмотря на свою полезность и простоту, многие не знают способы ее применения и незаслуженно обходят ее стороной.

С помощью данной утилиты можно производить некоторые этапы при проведении тестирования на проникновение. Это может быть полезно, когда на атакованной машине отсутствуют (или привлекут внимание) установленные пакеты, есть ограничения (например IoT/Embedded устройства) и т.д.

Что можно сделать с помощью netcat:

  • Сканировать порты;
  • Перенаправлять порты;
  • Производить сбор баннеров сервисов;
  • Слушать порт (биндить для обратного соединения);
  • Скачивать и закачивать файлы;
  • Выводить содержимое raw HTTP;
  • Создать мини-чат.

Вообще с помощью netcat можно заменить часть unix утилит, поэтому этот инструмент можно считать неким комбайном для выполнения тех или иных задач.

Практические примеры

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

Проверка наличия открытого TCP-порта 12345

nc: connect to 192.168.1.100 12345 (tcp) failed: Connection refused

Connection to 192.168.1.100 22 port [tcp/ssh] succeeded!
SSH-2.0-OpenSSH

Сканирование TCP-портов с помощью netcat:

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

nc: connectx to 192.168.1.100 port 20 (tcp) failed: Connection refused
nc: connectx to 192.168.1.100 port 21 (tcp) failed: Connection refused
found 0 associations
found 1 connections:
1: flags=82
outif en0
src 192.168.1.100 port 50168
dst 192.168.1.100 port 22
rank info not available
TCP aux info available
Connection to 192.168.1.100 port 22 [tcp/*] succeeded!
nc: connectx to 192.168.1.100 port 23 (tcp) failed: Connection refused
nc: connectx to 192.168.1.100 port 24 (tcp) failed: Connection refused

Сканирование UDP-портов.

Для сканирования UDP портов с помощью nmap необходимы root привилегии. Если их нет — в этом случае нам тоже может помочь утилита netcat:

Connection to 192.168.1.100 port 5555 [udp/*] succeeded!

Отправка UDP-пакета

Это может быть полезно при взаимодействии с сетевыми устройствами.

Прием данных на UDP-порту и вывод принятых данных

После первого сообщения вывод будет остановлен. Если необходимо принять несколько сообщений, то необходимо использовать while true:

Передача файлов. С помощью netcat можно как получать файлы, так и передавать на удаленный хост:

Netcact в роли простейшего веб-сервера.

Netcat может выполнять роль простейшего веб-сервера для отображения html странички.

C помощью браузера по адресу: http://хост netcat:8888/index.html. Для использования стандартного порта веб-сервера под номером 80 вам придется запустить nc c root привелегиями:

Чат между узлами

На первом узле (192.168.1.100):

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

Реверс-шелл

С помощью netcat можно организовать удобный реверс-шелл:

Теперь можно соединиться с удаленного узла:

Не стоит опускать руки, если нет тех или иных инструментов, зачастую довольно громоздких, иногда задачу можно решить подручными средствами.

Источник

Programming UDP sockets in C on Linux – Client and Server example

UDP sockets

This article describes how to write a simple echo server and client using udp sockets in C on Linux/Unix platform.

UDP sockets or Datagram sockets are different from the TCP sockets in a number of ways.

The most important difference is that UDP sockets are not connection oriented. More technically speaking, a UDP server does not accept connections and a udp client does not connect to server.

Читайте также:  Linux find files modified today

The server will bind and then directly receive data and the client shall directly send the data.

Simple UDP Server

So lets first make a very simple ECHO server with UDP socket. The flow of the code would be

socket() -> bind() -> recvfrom() -> sendto()

Run the above code by doing a gcc server.c && ./a.out at the terminal. Then it will show waiting for data like this

Next step would be to connect to this server using a client. We shall be making a client program a little later but first for testing this code we can use netcat.

Test the server with netcat

Open another terminal and connect to this udp server using netcat and then send some data. The same data will be send back by the server. Over here we are using the ncat command from the nmap package.

Note : We had to use netcat because the ordinary telnet command does not support udp protocol. The -u option of netcat specifies udp protocol.

Check open port with netstat

The netstat command can be used to check if the udp port is open or not.

Note the *:8888 entry of output. Thats our server program.
The entry that has localhost:8888 in «Foreign Address» column, indicates some client connected to it, which is netcat over here.

UDP Client

Now that we have tested our server with netcat, its time to make a client and use it instead of netcat.
The program flow is like

Here is a quick example

‘, BUFLEN); //try to receive some data, this is a blocking call if (recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen) == -1) < die("recvfrom()"); >puts(buf); > close(s); return 0; >

Run the above program and it will ask for some message

Whatever message the client sends to server, the same comes back as it is and is echoed.

Conclusion

UDP sockets are used by protocols like DNS etc. The main idea behind using UDP is to transfer small amounts of data and where reliability is not a very important issue. UDP is also used in broadcasting/multicasting.

When a file transfer is being done or large amount of data is being transferred in parts the transfer has to be much more reliable for the task to complete. Then the TCP sockets are used.

A Tech Enthusiast, Blogger, Linux Fan and a Software Developer. Writes about Computer hardware, Linux and Open Source software and coding in Python, Php and Javascript. He can be reached at [email protected] .

16 thoughts on “ Programming UDP sockets in C on Linux – Client and Server example ”

Hello. You seem to have double pasted the second code sample inside itself. THanks for the tutorial

Hey Silver Moon,

I’m a not a programmer but are very interested in electronics and making things automated. This was very helpful example of udp socket communications. What I did find though was the program doesn’t do anything else whilst it waits for data. How would you suggest to say send this server “Blink Led 1” and continue to listen for commands to turn on, blink or turn off leds.
I can for example blink the led no problem in one project, I can get you code also running on a pi and responding to commands I send it now but I would like to be able to continue doing things in the background.

Thanks for you time.

i haven’t done sockets for a long time. right now i can think of using multiple threads do things in parallel.
so the main thread could do its background work, and an extra thread could listen to the udp port for incoming messages.
or the other way round.
but i am not sure if that is the best approach. there might be better alternatives.

Silver Moon’s approach will work but the best way would be to listen for socket connections asynchronously using epoll() and using TCP not UDP, UDP is unreliable so some of your commands might not make it to the server as intended. That’s what is done in most modern socket servers. Try googling how to use epoll() (Linux system call so should work on Raspberry Pi). It will allow you to have an efficient and scalable socket server. (I am actually almost done developing an IoT socket communication system myself using raspberry pi as main server and epoll() with TCP is the best approach for this kind of stuff as far as I know.

Читайте также:  Windows 10 still free

Thx! This article was really helpful for understanding some basic things about socket programming.

Thank you so much for this, it was really helpful!

update note: Ubuntu 16.04.3. gcc 5.4.0 complained until slen was declared unsigned int.

And ncat used option -vv which on my Ubuntu system means verbose. The captured text does not have the verbose output. My system had five lines of information for each line of typed in data.
Still, I am new to Linux and Ubuntu and this is an unexpected cool way to test the server app.
Thank you.

Very helpful. Thanks!

Hi, I am new to socket programminga and linux , can you tell me … can we turn a system into a server ? and do communication using above programming? can we establish communication on the microcontroller using above programs?

Excelent example, thanks very much!
I’ve found that it needs only a tiny addition.
To clean the buffer on the server also. So just adding on Server:

//keep listening for data
while(1)
<
printf(“Waiting for data…”);
fflush(stdout);
memset(buf,’\0′, BUFLEN); //Add this line

if that sent character, how about send some file, example a picture, how to change in the script character sent to picture sent.

Please remove gets in Client:46 with:
fgets(message, BUFLEN, stdin);

What if the data sent from client side having some different Server address, SERVER 192.168.16.30 (this IP is pingable)

how to pass array , vector etc. between client and server?

if ((recv_len = recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen)) == -1)

here &slen should be (socklen_t*)&slen . and work perfectly. Thank u

Источник

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 )
>
Читайте также:  Linux запуск terminal от имени администратора

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.

Источник

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.

Источник

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