I want to write a kernel thread for an application that will read all UDP packets. I am facing problem in bindin开发者_运维问答g as these packet can arrive in range of ports (say 5001 to 5005).
How to do this. Any pointer/link will be helpful.
You can't bind a socket to more than one port, do as 0verbose suggested in a comment and use one socket per port
Besides opening multiple sockets, you need to use select()/poll() to listen to all sockets at once. If you are programming in C/C++ under Linux, here is a pseudo-code in C:
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
...
int main()
{
fd_set afds;
fd_set rfds;
int maxfd = -1;
int fd, ret;
/* initialize fdsets */
FD_ZERO(&afds);
/* create a socket per port */
foreach (port p) {
fd = create_udp_socket(p); /* also bind to port p */
if (fd < 0) error_exit("error: socket()\n");
FD_SET(fd, &afds);
if (fd > maxfd) maxfd = fd;
}
while (1) {
memcpy(&rfds, &afds, sizeof(rfds));
/* wait for a packet from any port */
ret = select(maxfd + 1, &rfds, NULL, NULL, NULL);
if (ret < 0) error_exit("error: select()\n");
/* which socket that i received the packet */
for (fd=0; fd<=maxfd; ++fd)
if (FD_ISSET(fd, &rfds))
process_packet(fd); /* read the packet from socket fd */
}
}
Hope this code will help you
精彩评论