- Федоренко на связи
- Заметки на полях
- Проверка COM порта под linux
- 5 комментариев (and 38 trackbacks)
- How to check if port is in use on Linux or Unix
- How to check if port is in use in
- Option #1: lsof command
- Option #2: netstat command
- Linux netstat syntax
- FreeBSD/MacOS X netstat syntax
- OpenBSD netstat syntax
- Option #3: nmap command
- A note about Windows users
- Conclusion
- Serial Port Programming on Linux
- Sourcecodes
Федоренко на связи
Заметки на полях
Проверка COM порта под linux
В этой заметке я расскажу про то, как можно проверить COM порт в Linux.
Для этого нам понадобятся:
- права на чтение и запись в COM порт
- программа minicom
- кусок толстого многожильного кабеля
Права доступа
проверяем какие у нас в системе есть COM порты, а также наши права на них:
/dev/ttyS0 это первый COM порт
/dev/ttyS1 соответственно второй COM порт
/dev/ttyUSB0 специальный кабель-переходник из USB в COM (Gembird UAS111)
Как мы видим для работы с COM портом необходимы права root либо пользователь должен входить в группу dialout
Провод для связи
Берём многожильный кабель в оплётке длиной 4-6 см, и соединяем 2 и 3 выводы COM порта перемычкой из этого кусочка провода. Оплётка будет удерживать провод на контактах, а металлические жилы внутри будут проводниками.
Для любителей паять можно предложить спаять полный loop-back тестер. В нём соединить не только контакты приёма передачи, но и аппаратный контроль потока и готовность терминала.
Работа с программой minicom
Для начала необходимо настроить программу minicom
Выбираем «Настройка последовательного порта»
Если нужно, меняем СОМ порт, нажимая «A»
Отключаем аппаратное управление потоком, нажимая «F»
Выходим из настроек «Enter»
Сохраняем настройки по умолчанию «Сохранить настройки как dfl»
Выходим из minicom
Собственно проверка СОМ порта
Запускаем minicom без параметров.
Пробуем нажимать на клавиши. В ответ на экране должны появляться символы.
Проверка COM порта под linux завершена.
Эта запись была сделана 21.12.2010, 13:50 под рубрикой Разное. Вы можете подписаться на эту запись с помощью RSS 2.0. Both comments and pings are currently closed.
5 комментариев (and 38 trackbacks)
#1 by Евгений on 02.05.2012 — 12:50
А как им управлять через PHP скрипт? Спасибо за статью!
Источник
How to check if port is in use on Linux or Unix
H ow do I determine if a port is in use under Linux or Unix-like system? How can I verify which ports are listening on Linux server? How do I check if port is in use on Linux operating system using the CLI?
It is important you verify which ports are listening on the server’s network interfaces. You need to pay attention to open ports to detect an intrusion. Apart from an intrusion, for troubleshooting purposes, it may be necessary to check if a port is already in use by a different application on your servers. For example, you may install Apache and Nginx server on the same system. So it is necessary to know if Apache or Nginx is using TCP port # 80/443. This quick tutorial provides steps to use the netstat, nmap and lsof command to check the ports in use and view the application that is utilizing the port.
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | Yes |
Requirements | lsof, ss, and netstat on Linux |
Est. reading time | 3 minutes |
How to check if port is in use in
To check the listening ports and applications on Linux:
- Open a terminal application i.e. shell prompt.
- Run any one of the following command on Linux to see open ports:
sudo lsof -i -P -n | grep LISTEN
sudo netstat -tulpn | grep LISTEN
sudo ss -tulpn | grep LISTEN
sudo lsof -i:22 ## see a specific port such as 22 ##
sudo nmap -sTU -O IP-address-Here - For the latest version of Linux use the ss command. For example, ss -tulw
Let us see commands and its output in details.
Option #1: lsof command
The syntax is:
$ sudo lsof -i -P -n
$ sudo lsof -i -P -n | grep LISTEN
$ doas lsof -i -P -n | grep LISTEN ### [OpenBSD] ###
Sample outputs:
Fig.01: Check the listening ports and applications with lsof command
Option #2: netstat command
You can check the listening ports and applications with netstat as follows.
Linux netstat syntax
Run netstat command along with grep command to filter out port in LISTEN state:
$ netstat -tulpn | grep LISTEN
The netstat command deprecated for some time on Linux. Therefore, you need to use the ss command as follows:
sudo ss -tulw
sudo ss -tulwn
sudo ss -tulwn | grep LISTEN
Where, ss command options are as follows:
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
- -t : Show only TCP sockets on Linux
- -u : Display only UDP sockets on Linux
- -l : Show listening sockets. For example, TCP port 22 is opened by SSHD server.
- -p : List process name that opened sockets
- -n : Don’t resolve service names i.e. don’t use DNS
FreeBSD/MacOS X netstat syntax
$ netstat -anp tcp | grep LISTEN
$ netstat -anp udp | grep LISTEN
OpenBSD netstat syntax
$ netstat -na -f inet | grep LISTEN
$ netstat -nat | grep LISTEN
Option #3: nmap command
The syntax is:
$ sudo nmap -sT -O localhost
$ sudo nmap -sU -O 192.168.2.13 ##[ list open UDP ports ]##
$ sudo nmap -sT -O 192.168.2.13 ##[ list open TCP ports ]##
Sample outputs:
Fig.02: Determines which ports are listening for TCP connections using nmap
A note about Windows users
You can check port usage from Windows operating system using following command:
netstat -bano | more
netstat -bano | grep LISTENING
netstat -bano | findstr /R /C:»[LISTEING]»
Conclusion
This page explained command to determining if a port is in use on Linux or Unix-like server. For more information see the nmap command and lsof command page online here
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
Serial Port Programming on Linux
This is a tutorial on how to program the Serial Ports on your Linux box.Serial Ports are nice little interfaces on the PC which helps you to interface your embedded system projects using a minimum number of wires.In this tutorial we will write a small program that will send and receive ASCII characters to a microcontroller development board.
One problem with the traditional serial ports is that they are now legacy hardware and are being phased out by the PC manufacturers and most laptops have USB ports only,this problem can be easily solved by using a variety of USB to Serial Converters available in the market,eg USB2SERIAL V2.0.
Please note that in this tutorial I am using a USB to Serial Converter based on FT232 from FTDI. You can use any FT232 based board ( other USB converter boards based on different chip sets should work,but i have not tested it ) or you can buy the one I am using here.
If you have traditional D subminiature (DB9) Serial Ports,just identify the relevant pins (RXD, TXD,RTS,DTR and Ground) and continue with the tutorial.
In this tutorial we are going to use the C language to program the serial port on a Linux Operating system(Ubuntu/LinuxMint).The compiler used is gcc which is freely available along with the OS.
Sourcecodes
- Please note that the source codes on the website show only the relevant sections to highlight the process of programming the serial port.
- Contact Us to Enquire about the full Source codes
Serial Ports under Linux
Traditional hardware serial ports under Linux are named as ttyS* where * can be 1,2,3. etc for eg ttyS1,ttyS2,ttyS23 . etc.They are similar to COM1,COM2 etc under a windows box.
While
USB to Serial Converter based serial ports are usually named as ttyUSB* where * can be 1,2,3. etc for eg ttyUSB0,ttyUSB1 etc .
In Linux the hardware components like serial ports are treated like files and are grouped together in the /dev folder in the file system.if you navigate into the /dev folder and list the files using ls command you can see the files corresponding to various hardware devices.
Now you can see a large number of serial ports listed in the /dev directory like ttyS28,ttyS23 etc.Now to identify which of the ttyS* corrosponds to your hardware serial port run the following command on the terminal.
dmesg | grep ttyS
if you are getting an output like this
[ 37.531286] serial8250: ttyS0 at I/O 0x3f8 (irq = 4) is a 16550A
it means that ttyS0 is your hardware serial port connected to your computer .
Now if you dont have any hardware serial ports ( like in my case ) the command will not print anything,like this.
Now to check for any USB to serial converter use dmesg | grep tty command.
You can see that FTDI based USB to Serial Converter is attached to ttyUSB0.Now you can use the ttyUSB0 to communicate with your serial converter .
Another place where you can see the attached serial devices is the /dev/serial/by-id folder.
Programming the Serial Port
In this tutorial i am going to use C language to program the Serial port,compiler used is GCC.
If you are interested to know more about the internals of the serial port you can refer “The Serial Programming Guide for POSIX Operating Systems” written by Michael R.Sweet.
To perform serial I/O under linux we are going to use the termios API.termios API supports two modes of accessing the serial ports.
1. Cannonical Mode
2. NonCannonical Mode
Cannonical mode is the default mode and is used for accessing terminals and stuff.For our tutorial we are going to use the second mode called the non cannonical mode.More details about the difference between the modes are available in the above book .
Opening and Closing the Serial Port
Opening a serial port in Linux is accomplished by using the open() system call and closing the serial port is done using the close() system call.
The open() system call takes two arguments ,name of the file to be opened (here serial port ) and the various parameters associated with it.It returns a -1 on failure and a positive integer on success.
int fd ;
fd = open( » /dev/ttyUSB0 «,O_RDWR | O_NOCTTY ) ;
here /dev/ttyUSB0 is the name of the serial port you are using (here FTDI based USB2SERIAL Converter board),If you are using a hardware serial port it will be some thing like /dev/ttyS1 or /dev/ttyS2.
gcc -o serial serial.c Now save the file and compile it using GCC at the terminal.
Please make sure that you are using the correct serial port name in the open() command.In the above code it is ttyUSB0 , it may be different in your system.
Another important fact regarding the Linux system is that Linux will only allow you to access the hardware resources from root account.So you will have to execute the resulting binary as root ,just use the sudo command.
After the code is compiled successfully,execute the binary as root by issuing the following command.Enter the password for root when prompted.
sudo ./serial
Please make sure your hardware is connected before executing the binary, in case you are using a USB to serial converter.
Configuring the termios structure
After opening and closing the serial port successfully ,its time to configure the correct mode,baudrate,data format,number of start/stop bits etc .In Linux it is done by a structure called termios.
And this is how the structure looks like
struct termios
<
tcflag_t c_iflag ; /* input mode flags */
tcflag_t c_oflag ; /* output mode flags */
tcflag_t c_cflag ; /* control mode flags */
tcflag_t c_lflag ; /* local mode flags */
cc_t c_line ; /* line discipline */
cc_t c_cc[NCCS] ; /* control characters */
>;
Now first thing to do is to declare a structure of type termios
struct termios SerialPortSettings ;
Now to configure the termios structure according to our needs we use two functions,tcgetattr() and tcsetattr().
tcgetattr() is used to get the current settings of the serial port to the structure we just declared.It takes two arguments, the file descriptor fd corresponding to the serial port we have opened and the address of the structure we just declared.
After getting the current settings we are going to change it suit our needs.We are going to configure the serial port to transmit at 9600 baudrate , 8 bits, No parity ,1 Stop bit ,the 8N1 configuration.
Setting the Baudrate
In Linux ,there is an option to set different read and write speeds but it is recommended to set the same speed for both read and write.
The Baudrate is set using two functions,
cfsetispeed() for setting the input speed or read speed and
cfsetospeed() for setting the output speed or write speed.
Now let’s set the speed for both reading and writing at 9600 bps
you can use other standard baudrates like 4800,19200,38400 etc all Baudrate constants have to be prefixed with a ‘B’ like B4800 , B19200 etc .
Please note that the MSP430 microcontroller code provided (microcontroller side) uses 9600bps 8N1 format for communicating with the PC.
Configuring data format,Start/Stop bits ,Parity
The control flags ( c_cflag ) of the termios structure configures the data format (8bit or 7 bits for data),Parity(Even,Odd,None) and the number of start and stop bits to use while communicating.
Configuring these information involves setting and clearing individual bits of the control flags.It is advisable to check out “Bit manipulation in C language” in google/wikipedia,if you are not familiar.
Configuring other Options
Turn off hardware based flow control (RTS/CTS).
Turn on the receiver of the serial port (CREAD),other wise reading from the serial port will not work.
SerialPortSettings.c_cflag |= CREAD | CLOCAL ;
Turn off software based flow control (XON/XOFF).
( IXON | IXOFF | IXANY );
Setting the mode of operation,the default mode of operation of serial port in Linux is the Cannonical mode.For Serial communications with outside devices like serial modems,mice etc NON Cannonical mode is recommended.
( ICANON | ECHO | ECHOE | ISIG );
More information about the functions and constants discussed above can be found in the termios manual page.You can easly access them by typing
man termios on your terminal.
The man pages are also available online at www.man7.org.
After you have configured all of the required bitfields of the terminos structure.You can use the tcsetattr() function to set them.tcsetattr() takes three arguments,the first and last arguments are same as in the tcgetattr()function.The second one TCSANOW tells to make the changes now without waiting.
tcsetattr ( fd , TCSANOW , &SerialPortSettings )
Hardware Connections
Now we will create a small serial link between a microcontroller board and a PC running Linux OS to test out reading and writing from a PC serial port .
Microcontroller used here is MSP430G2553 from Texas instruments on Launchpad development board.Please note that you can use any microcontroller like 8051 or Atmel AVR on the embedded system side.Since this is an article about setting up and configuring the serial port on Linux,the microcontroller side code is explained here.
The PC is connected to the microcontroller board using a null modem cable.The RX of the PC (serial port) is connected to the TX of the Microcontroller and vice versa.The Grounds of PC and microcontroller are connected together.
Here my PC do not have a hardware DB9 serial port(9 pin),So i am using a FTDI based USB to Serial converter called USB2SERIAL which converts the USB signals to TTL compatible serial outputs (RXD and TXD). you can directly connect the outputs of USB2SERIAL to MSP430 microcontroller as shown in the below block diagram. USB2SERIAL also offers selectable 3V/5V TTL outputs for interfacing to 3.3V logic microcontrollers like MSP430.
Please noter that if you are using a DB9 RS232 SerialPort of your PC ,you will have to build a RS232 signal level converter at the microcontroller side to decode the RS232 signal.Connecting the RS232 Lines from the PC directly to microcontroller UART directly will damage the chip.
Writing data into Serial Port
Writing data to serial port is accomplished using the write() system call.
Reading Data from the Serial Port
Reading data from the serial port is accomplished by using the read() system call.
In the zip file you can find “SerialPort_read.c” which contains the complete program.Compile the program using gcc and run it.Remember to use sudo so that your executable runs as root.
After providing the root password,the program will execute and wait for a character to be send by the microcontroller.
You can now reset the MSP430 microcontroller connected to the USB2SERIAL converter to transmit the string .
Program receives the “Hello from MSP430” string send by the microcontroller and displays it on the terminal.
Источник