36 #include <sys/types.h> 37 #include <sys/socket.h> 39 #include <netinet/ip.h> 40 #include <netinet/in.h> 41 #include <arpa/inet.h> 48 struct sockaddr_in recvaddr;
50 if ((insock = socket(PF_INET,SOCK_DGRAM,0)) == -1)
57 memset(&recvaddr, 0,
sizeof(recvaddr));
58 recvaddr.sin_family = AF_INET;
59 recvaddr.sin_addr.s_addr = INADDR_BROADCAST;
60 recvaddr.sin_port = htons(1234);
62 if (bind(insock, (
struct sockaddr*) &recvaddr,
sizeof recvaddr) == -1)
64 ROS_ERROR(
"Can't bind to socket to receive.");
77 struct sockaddr_in sendaddr;
78 struct sockaddr_in recvaddr;
80 if ((outsock = socket(PF_INET,SOCK_DGRAM,0)) == -1)
82 ROS_ERROR(
"Error opening output socket.");
87 memset(&sendaddr, 0,
sizeof(sendaddr));
88 sendaddr.sin_family = AF_INET;
89 sendaddr.sin_addr.s_addr = ((sockaddr_in *) iface->ifa_addr)->sin_addr.s_addr;
90 sendaddr.sin_port = htons(srcport);
92 if (bind(outsock, (
struct sockaddr*) &sendaddr,
sizeof sendaddr) == -1)
94 ROS_ERROR(
"Can't bind to socket on interface %s.", iface->ifa_name);
100 if ((setsockopt(outsock,SOL_SOCKET,SO_BROADCAST, &broadcast,
sizeof broadcast)) == -1)
102 ROS_ERROR(
"Can't set broadcast flag on interface %s.", iface->ifa_name);
107 memset(&recvaddr, 0,
sizeof(recvaddr));
108 recvaddr.sin_family = AF_INET;
109 recvaddr.sin_port = htons(port);
110 recvaddr.sin_addr.s_addr = INADDR_BROADCAST;
112 char outpkt[] = { 0x42, 0x11, 0x00, 0x02, 0x00, 0x00, 0x06, 0x26 };
114 if (sendto(outsock, outpkt,
sizeof(outpkt) , 0, (
struct sockaddr *)&recvaddr,
sizeof(recvaddr)) !=
sizeof(outpkt))
116 ROS_ERROR(
"Failed sending packet on interface %s.", iface->ifa_name);
127 ROS_INFO(
"Got a response on socket %i.", fd);
141 memcpy(&tmpset, master_set,
sizeof(tmpset));
142 retval = select(maxfd + 1, &tmpset, NULL, NULL, &tv);
144 if (retval < 0 && errno != EINTR)
146 ROS_ERROR(
"Select exited with an error code.");
154 for (
int i = 0; i <= maxfd && retval > 0; i++)
155 if (FD_ISSET(i, &tmpset))
165 struct sockaddr localPort;
166 socklen_t localPortLen;
168 if (getsockname(fd, &localPort, &localPortLen) == -1)
170 ROS_ERROR(
"Unable to get local port for socket.");
174 return ntohs(((
struct sockaddr_in *)&localPort)->sin_port);
179 struct ifaddrs *ifaces = NULL;
183 if (getifaddrs(&ifaces))
185 ROS_ERROR(
"Couldn't get interface list.");
193 FD_SET(maxfd, &fdset);
197 for (
struct ifaddrs *curif = ifaces; curif; curif = curif->ifa_next)
199 if (curif->ifa_addr && curif->ifa_addr->sa_family == AF_INET)
int get_local_port(int fd)
void get_response(int fd)
int collect_replies(fd_set *master_set, int maxfd)
int send_query(struct ifaddrs *iface, int srcport)