简体   繁体   中英

Active services (ports) using sockets

I´m going to program an application that shows if there is an active/inactive service in a range of UDP ports, of a given IP.

My first intention it's trying to bind a socket with an address (the port is included in the address). Bind will return -1 if fails, with an errno EADDRINUSE, that means that the specified address is already in use. If the bind is done, I will close the socket, and go to the next port.

I'm a bit lost with sockets and networks things, so I would like to know if my approach is correct, or a clue about the best way to do that.

Thanks

在Windows上,您可以使用GetUdpTable()GetUdp6Table()向操作系统询问活动的IPv4 / IPv6 UDP套接字列表(TCP套接字有相应的功能)。

In Linux, the /proc/net/udp file lists all open UDP sockets. The 2nd column in the file shows the interface address and port number (in hex):

[root@localhost ~]# head -n 2 /proc/net/udp
  sl  local_address rem_address   st tx_queue rx_queue tr tm->when retrnsmt   uid  timeout inode
  33: 00000000:00A1 00000000:0000 07 00000000:00000000 00:00000000 00000000     0        0 9236 2 ffff8102205a8980

Alternatively you can run netstat -au (on POSIX systems you can use the popen() system call to run a program and capture its output as a FILE * ):

[root@localhost ~]# netstat -au
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address               Foreign Address             State
udp        0      0 *:snmp                      *:*

Your bind() technique is not reliable because UDP allows multple bound sockets to the same addresses (depending on socket settings).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM