UDP socket (publishing to topic)

asked 2015-12-02 08:07:09 -0600

Victoria_W gravatar image

updated 2015-12-07 04:38:51 -0600

Hello,

I would like to write an UDP socket in C++, which publishes packets (which have been sent to a certain port) to a ros topic. I already studied the ros::TransportUDP Class Reference, and found the function createIncoming(). There is kind of an example code in transport_udp.cpp (line 234-270), but since I am new to UDP and ROS, I am not sure how to create my own socket out of that (libraries I would have to include/initialization/how to adapt the code below/etc.).

Is there anyone who could help? Thanks a lot!

(something for TCP as an orientation would be okay to, but I would prefer UDP since I need to write it for the latter)


The code excerpt from transport_udp.cpp:

00234 bool TransportUDP::createIncoming(int port, bool is_server)
00235 {
00236   is_server_ = is_server;
00237 
00238   sock_ = socket(AF_INET, SOCK_DGRAM, 0);
00239 
00240   if (sock_ <= 0)
00241   {
00242     ROS_ERROR("socket() failed with error [%s]", last_socket_error_string());
00243     return false;
00244   }
00245 
00246   server_address_.sin_family = AF_INET;
00247   server_address_.sin_port = htons(port);
00248   server_address_.sin_addr.s_addr = isOnlyLocalhostAllowed() ? 
00249                                     htonl(INADDR_LOOPBACK) :
00250                                     INADDR_ANY;
00251   if (bind(sock_, (sockaddr *)&server_address_, sizeof(server_address_)) < 0)
00252   {
00253     ROS_ERROR("bind() failed with error [%s]",  last_socket_error_string());
00254     return false;
00255   }
00256 
00257   socklen_t len = sizeof(server_address_);
00258   getsockname(sock_, (sockaddr *)&server_address_, &len);
00259   server_port_ = ntohs(server_address_.sin_port);
00260   ROSCPP_LOG_DEBUG("UDPROS server listening on port [%d]", server_port_);
00261 
00262   if (!initializeSocket())
00263   {
00264     return false;
00265   }
00266 
00267   enableRead();
00268 
00269   return true;
00270 }
edit retag flag offensive close merge delete

Comments

1

Hello Did you find the solution? Can you help me for similar question?

Masoud gravatar image Masoud  ( 2017-04-24 01:29:20 -0600 )edit